package ch10;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseDemo extends JFrame implements MouseMotionListener{
private JPanel p;
private JButton btn;
int x,y;
public MouseDemo() {
super("画板");
p = new JPanel();
//注册鼠标监听
p.addMouseMotionListener(this);
btn = new JButton("重新画图");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 清空画板
p.getGraphics().clearRect(0, 0, p.getWidth(), p.getHeight());
}
});
p.add(btn);
this.add(p);
this.setSize(400,300);
this.setLocation(100,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//重写JFrame的paint()方法
public void paint(Graphics g) {
//设置画笔颜色
g.setColor(Color.blue);
//画一个实心圆
g.fillOval(x, y, 5, 5);
}
//鼠标移动的处理方法
public void mouseDragged(MouseEvent e) {
//获取坐标
x=e.getX();
y=e.getY();
//重画,repaint()触发paint()
this.repaint();
}
//鼠标移动的处理方法
public void mouseMoved(MouseEvent e) {
}
public static void main(String[] args) {
MouseDemo f = new MouseDemo();
f.setVisible(true);
}
}
java实现拖鼠标在面板中画图功能
最新推荐文章于 2023-01-10 21:20:08 发布