Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between mouseListener and mouseMotionListener in Java?

Is mouseMotionListener going to trigger an event once the mouse moves over the component, whereas mouseListener only triggers if I press a button?

So if I have only a mousePressed event, then I don't need a mouseMotionListener? Only if I had a mouseEntered or mouseExited?

like image 664
zxcvbnm Avatar asked Dec 29 '22 10:12

zxcvbnm


2 Answers

Yes, you are correct. mouseMotionListener is used to perform actions when your mouse moves over a "hotspot"

Good example can be found here

When dealing with mousePressed events, you only need mousePressed events unless you wanted to add more events to perform while the mouse is hovered.

like image 189
Anthony Forloney Avatar answered Jan 13 '23 12:01

Anthony Forloney


They listen for different events:

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.

Add the listeners according to what event you're after.

like image 29
Pool Avatar answered Jan 13 '23 11:01

Pool