package com.wang.gui;
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 MyFrame2("画图");
}
}
//自己的类
class MyFrame2 extends Frame {
//画画需要画笔,需要监听鼠标当前的位置,需要集合
ArrayList points = null;
public MyFrame2(String title) {
super(title);
setBounds(200, 200, 400, 300);
//存鼠标点击的点
points = new ArrayList<>();
this.addMouseListener(new MyMouseListener());
setVisible(true);
}
@Override
public void paint(Graphics g) {
//画画,监听鼠标的事件
Iterator iterator = points.iterator();
while (iterator.hasNext()) {
Point point = (Point) iterator.next();
g.setColor(Color.BLUE);
g.fillOval(point.x, point.y,10,10);
}
}
//添加一个点到界面上
private void addPaint(Point point){
points.add(point);
}
//适配器模式
private class MyMouseListener extends MouseAdapter {
//鼠标 按下,弹起,按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame2 frame = (MyFrame2) e.getSource();
//这个我们点击的时候,就会在界面上产生一个点!画
//这个点就是鼠标的点;
frame.addPaint(new Point(e.getX(), e.getY()));
//每次点击鼠标都需要重新画一遍
frame.repaint();//刷新
}
}
}