Java Swing(七):鼠标事件MouseEvent
鼠标事件MouseEvent
可以给控件/界面添加鼠标事件有三种监听器:
1.addMouseListener 点击,按住,抬起,移入,移出
2.addMouseMotionListener 移动,拖动
3.addMouseWheelListener 鼠标滚轮转动
MouseListener接口下要覆盖五个方法:mouseClicked,mouseEntered,mouseExited,mousePressed,mouseReleased分别对应不同的鼠标事件。
对于鼠标事件MouseEvent的常用方法:
getX()/getY 获取当前点击位置的坐标(相对于界面)
getXOnScreen()/getYOnSreen() 获取当前点击位置的坐标(相对于屏幕)
getSource() 点击的控件
getButton() 左键/中建/右键
getClickCount() 单机/双击/三击
由于每次使用MouseListener接口都要重写五个方法,所以改用抽象类MouseAdapter,要用哪个就写哪个。
以mouseClicked为例代码:
root.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e){ if(e.getButton() == MouseEvent.BUTTON1) System.out.println("左键"); else if(e.getButton() == MouseEvent.BUTTON2) System.out.println("中键"); else if(e.getButton() == MouseEvent.BUTTON3) System.out.println("右键"); int cc = e.getClickCount(); if(cc == 1) System.out.println("单机"); else if(cc == 2) System.out.println("双击"); System.out.println("鼠标位置:" + e.getX() + "," + e.getY()); System.out.println("------------"); } });
MouseWheelListener滚轮事件
例:
MouseWheelListener wheelListener = new MouseWheelListener(){ @Override public void mouseWheelMoved(MouseWheelEvent e){ Image image = canvas.getImage(); int i; for(i=0;i<buttons.size();i++){ if(buttons.get(i).getImage()==image) break; } ThumbButton button = buttons.get(i); if(e.getUnitsToScroll()>0){ //滚轮向下时e.getUnitsToScroll()大于0 button = nextImage(i); }else{ //滚轮向上时e.getUnitsToScroll()小于0 button = lastImage(i); } setBlueBorder(button); } };
————————————————
版权声明:本文为CSDN博主「Cobb141」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Cobb141/article/details/108967016