Java中mouseListener和mouseMotionListener的区别?

时间:2009-11-25 17:27:57

标签: java user-interface mouse

一旦鼠标在组件上移动,mouseMotionListener是否会触发事件,而只有按下按钮时,mouseListener才会触发?

所以如果我只有一个mousePressed事件,那么我不需要mouseMotionListener?只有我有一个mouseEntered或mouseExited?

2 个答案:

答案 0 :(得分:5)

是的,你是对的。 mouseMotionListener用于在鼠标移过“热点”时执行操作

可以找到好的例子here

处理mousePressed事件时,您只需要mousePressed个事件,除非您想要在鼠标悬停时添加更多要执行的事件。

答案 1 :(得分:5)

他们会听取不同的事件:

MouseListener

mouseClicked(MouseEvent event)   // Called just after the user clicks the listened-to component.
mouseEntered(MouseEvent event)   // Called just after the cursor enters the bounds of the listened-to component.
mouseExited(MouseEvent event)    // Called just after the cursor exits the bounds of the listened-to component.
mousePressed(MouseEvent event)   // Called just after the user presses a mouse button while the cursor is over the listened-to component.
mouseReleased(MouseEvent event)  // Called just after the user releases a mouse button after a mouse press over the listened-to component

MouseMotionListener

mouseDragged(MouseEvent event)   // Called in response to the user moving the mouse while holding a mouse button down. This event is fired by the component that fired the most recent mouse-pressed event, even if the cursor is no longer over that component.
mouseMoved(MouseEvent event)     // Called in response to the user moving the mouse with no mouse buttons pressed. This event is fired by the component that's currently under the cursor.

根据您追踪的事件添加侦听器。