GUI 鼠标监听事件,模拟画图工具

编写代码 TestMouseListener测试类

package com.xiang.lesson03;

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.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;

//鼠标监听事件
public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}

//自己的鼠标类
class MyFrame extends Frame {
    //需要画笔,与监听鼠标当前位置,需要集合来存储这个点
    AbstractList points;

    //构造器
    public MyFrame(String title) {
        super(title);
        setVisible(true);
        setBounds(200, 200, 600, 500);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
//        存放鼠标点击 的点
        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, 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();
        }
    }
}

运行结果

思路

posted @ 2021-08-06 18:12  阿向向  阅读(42)  评论(0编辑  收藏  举报