鼠标监听事件,模拟画图工具
1 public class TestMouseListener { 2 public static void main(String[] args) { 3 new MyFrame01("鼠标监听事件"); 4 } 5 } 6 class MyFrame01 extends Frame{ 7 ArrayList points; 8 public MyFrame01(String title){ 9 super(title); 10 points = new ArrayList<>(); 11 setBounds(200,200,400,400); 12 setVisible(true); 13 this.addMouseListener(new MyMouseLstener()); 14 } 15 16 @Override 17 public void paint(Graphics g) { 18 super.paint(g); 19 Iterator iterator=points.iterator(); 20 while (iterator.hasNext()){ 21 Point point= (Point) iterator.next(); 22 g.setColor(Color.red); 23 g.fillOval(point.x,point.y,100,100); 24 } 25 } 26 27 28 class MyMouseLstener extends MouseAdapter{ 29 30 @Override 31 public void mouseClicked(MouseEvent e) {
//e代表着鼠标,这里的e.getSourse()意思是返回添加监听器的对象为Object类型,需要转换为Frame类 32 MyFrame01 guo =(MyFrame01) e.getSource(); 33 Point point=new Point(e.getX(),e.getY()); 34 points.add(point); 35 guo.repaint(); 36 } 37 } 38 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义