package Paint;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
//鼠标监听事件
public class MouseListenerTest {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame("画图");
close(myFrame);
}
//关闭窗口方法
private static void close(Frame frame) {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//窗体类
class MyFrame extends Frame {
ArrayList points;
//画画需要画笔,需要监听鼠标当前的位置,需要用集合来存储这个点
public MyFrame(String title) {
super(title);
setBounds(200, 200, 400, 300);
setVisible(true);
//存取鼠标的点
points = new ArrayList<>();
//鼠标监听器
this.addMouseListener(new MyMouseListener());
}
@Override
public void paint(Graphics g) {
//画画,监听鼠标的事件
Iterator iterator = points.iterator();
while (iterator.hasNext()) {
Point point = (Point) iterator.next();
g.setColor(Color.red);
g.fillOval(point.x, point.y, 50, 50);
}
}
//添加点到界面上
public void addPaint(Point point) {
points.add(point);
}
//内部类
private class MyMouseListener extends MouseAdapter {
//鼠标按下
@Override
public void mousePressed(MouseEvent e) {
MyFrame myFrame = (MyFrame) e.getSource();
//点击时,产生一个点
myFrame.addPaint(new Point(e.getX(), e.getY()));
//刷新
myFrame.repaint();
}
}
}
GUI—Paint的使用
最新推荐文章于 2023-06-22 11:08:19 发布