如下界面可以通过该界面研究一下Swing的鼠标事件:
图中用红粗线圈起来的为JtextPanel,该Panel添加了鼠标事件监听器,鼠标事件监听器有三种,分别为MouseWheelListener,MouseMotionListener和MouseListener分别用来监听鼠标的滑轮事件,鼠标的移动事件,和一般的鼠标事件。
通过给JtextPanel添加鼠标事件监听器和加上打印信息后很容易就能摸得着鼠标事件的规律,滑轮事件不用说了,鼠标移动事件包括Dragged和Moved,这两种事件只要鼠标在移动不论是动还是被按住拖拽都会不断的触发事件, 一般鼠标事件有Pressed,Released,Clicked,Entered,Exited,以选中TextPanel中下面的一段文字进行说明各事件:只要鼠标在TextPanel中移动就不断的触发Moved,离开TextPanel区域就会触发Exited,进入则有Entered, 鼠标点击则Clicked(其实还包括Pressed和Released),选中的过程中开始有Pressed,中间是不断的Dragged,结束后是Released. 其实很容易记,下次记住就不用每次都做实验了!
下面是代码片段
docTextPane = new JTextPane(); docTextPane.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { System.out.println("Mouse WheelMoved"); } }); docTextPane.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { System.out.println("Mouse Dragged"); } @Override public void mouseMoved(MouseEvent e) { System.out.println("Mouse mouse Moved"); } }); docTextPane.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.out.println("Mouse mouse Pressed"); } @Override public void mouseReleased(MouseEvent e) { System.out.println("Mouse mouse Released"); } @Override public void mouseClicked(MouseEvent e) { System.out.println("Mouse mouse Clicked"); } @Override public void mouseEntered(MouseEvent e) { System.out.println("Mouse mouse Entered"); } @Override public void mouseExited(MouseEvent e) { System.out.println("Mouse mouse Exited"); } });