11:鼠标监听事件、模拟画图工具
需求:想要实现鼠标画画!
分析:画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
思路:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.gui.lesson3; 2 3 import java.awt.*; 4 import java.awt.event.MouseAdapter; 5 import java.awt.event.MouseEvent; 6 import java.util.ArrayList; 7 import java.util.Iterator; 8 9 //测试鼠标监听事件 10 public class TestMouseListener { 11 public static void main(String[] args) { 12 MyFrame frame = new MyFrame("画图"); 13 14 } 15 } 16 17 //1.自己的类 18 class MyFrame extends Frame { 19 //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点 20 ArrayList points; 21 22 public MyFrame(String title) { 23 super(title); 24 setBounds(200, 200, 400, 300); 25 //5.存鼠标点击的点 26 points = new ArrayList<>(); 27 setVisible(true); 28 //2.鼠标监听器,正对这个窗口 29 this.addMouseListener(new MyMouseListener()); 30 } 31 32 @Override 33 public void paint(Graphics g) { 34 //7.画画,需要监听鼠标的事件 35 Iterator iterator = points.iterator(); 36 while (iterator.hasNext()) { 37 Point point = (Point) iterator.next(); 38 g.setColor(Color.BLUE); 39 g.fillOval(point.x, point.y, 10, 10); 40 } 41 } 42 43 //8.添加一个点到界面上 44 public void addPaint(Point point) { 45 points.add(point); 46 } 47 48 //3.适配器模式:MouseListener是个接口,我们继承它的实现类即可,避免重写多余的方法 49 private class MyMouseListener extends MouseAdapter { 50 //重写快捷键:Ctrl+O 51 //鼠标 按下,弹起,按住不放 52 53 54 @Override 55 public void mousePressed(MouseEvent e) { 56 MyFrame frame = (MyFrame) e.getSource(); 57 //4.这个地方点击的时候,就会在界面上产生一个点!点需要画出来,所以写画的代码 58 //6.这个点就是鼠标的点; 59 //new Point(e.getX(), e.getY()); 60 //9.把这个点通过addPoint()传到集合里面,通过画笔把它画出来 61 frame.addPaint(new Point(e.getX(), e.getY())); 62 63 //10.每次点击鼠标都需要重新画一遍 64 frame.repaint();//刷新 65 } 66 } 67 }
效果图:
北斗第一阳明司命星君 (天枢)
北斗第二阴精司禄星君 (天璇)
北斗第三真人禄存星君 (天玑)
北斗第四玄冥延寿星君 (天权)
北斗第五丹元益算星君 (玉衡)
北斗第六北极度厄星君 (开阳)
北斗第七天关上生星君 (摇光)