package com.zym.lesson11; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Iterator; //测试鼠标监听事件 public class TestMouseListener { public static void main(String[] args) { new MyFrame11("lesson11:鼠标监听事件-绘点"); } } class MyFrame11 extends JFrame{ ArrayList points; //1 画笔 2鼠标位置 3 需要集合来存储这些点 public MyFrame11(String title){ super(title); setBounds(100,100,400,200); //存鼠标坐标点 points=new ArrayList(); //添加鼠标监听器 this.addMouseListener(new Zym_MouseListener()); //设置可见 setVisible(true); addWindowListener(new WindowAdapter() { //窗体关闭时做的事 @Override public void windowClosing(WindowEvent e) { // super.windowClosed(e); System.exit(0); } } ); } @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 p){ points.add(p); } //适配器模式 ,监听器类 private class Zym_MouseListener extends MouseAdapter { //鼠标点击 鼠标按住 鼠标弹起 @Override public void mousePressed(MouseEvent e) { MyFrame11 myFrame11=(MyFrame11) e.getSource(); //获得当前鼠标的点 myFrame11.addPaint(new Point(e.getX(),e.getY())); //每次点击鼠标,需要它重画一遍 myFrame11.repaint(); } } }
标签:MyFrame11,鼠标,void,绘点,lesson11,import,new,public From: https://www.cnblogs.com/zym97816/p/17762412.html