Gui: TestMouseLinstener


import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;

public class TestMouseLinstener {
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}
class MyFrame extends Frame {
    ArrayList points;

    public MyFrame(String title) {
        super(title);
        setBounds(200, 200, 400, 300);
        //存放鼠标点
        points = new ArrayList<>();
        setVisible(true);
        //监听鼠标
        this.addMouseListener(new MyMouseListener());
    }

    public void paint(Graphics g) {
        //迭代
        Iterator iterator = points.iterator();
        while (iterator.hasNext()) {
            Point point = (Point) iterator.next();
            g.setColor(Color.cyan);
            g.fillOval(point.x, point.y, 10, 10);
        }
    }

    public void addPaint(Point point) {
        points.add(point);
    }


    private class MyMouseListener extends MouseAdapter {


        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame= (MyFrame) e.getSource();
            frame.addPaint(new Point(e.getX(),e.getY()));
            frame.repaint();//refresh
        }

    }

}

你可能感兴趣的:(Gui,java,开发语言)