视频链接:11、鼠标监听事件、模拟画图工具_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1DJ411B75F?p=11&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5
模拟画图工具的实现逻辑图:
实现代码:
package com.yundait.lesson03;import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;public class TestMouseListener {public static void main(String[] args) {new MyFrame("画图");}
}//创建自己的"画图"窗口
class MyFrame extends Frame{ArrayList points;public MyFrame(String title){super(title);//调用父类构造方法setBounds(200,200,500,400);//存鼠标点击的点points = new ArrayList<>();//鼠标监听器,针对这个窗口this.addMouseListener(new MyMouseListener());setVisible(true);}//重写画笔方法@Overridepublic 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);}}//写一个自己的鼠标监听类(内部类)private class MyMouseListener extends MouseAdapter {@Overridepublic void mousePressed(MouseEvent e) {MyFrame myFrame = (MyFrame) e.getSource();//获取事件源对象//这里我点击的时候,就会在界面上产生一个点!//这个点就是鼠标的点;myFrame.points.add(new Point(e.getX(), e.getY()));//每次点击鼠标都需要重新画一遍myFrame.repaint();//重新画点,刷新界面;}}
}
运行结果:可以在画板上通过鼠标点击不停地画点。