Java Made Clear: Java Mouse Event Mouse Click Example

When mouse is clicked, mouse generates an event called mouse event represented by MouseEvent class. MouseEvent is handled by MouseListener. Explained in simple terms.

Whenever, a GUI component is interacted by the user, it generates an event. For example, if the user clicks over a button, the button generates an event known as ActionEvent. Similarly, when the user selects a check box, it generates an event and the event is known as ItemEvent. These two examples refer software components. Java also supports events generated by hardware components like mouse and keyboard etc.

Whenever, a mouse is clicked by user, it generates MouseEvent and similarly KeyEvent for keyboard. That is, a mouse click generates mouse event. Capturing the event and performing some action is known as event handling. To do event handling with mouse event, there comes two interfaces in Java – MouseListener and MouseMotionListener.

Finally to say:

Whenever, a user clicks a mouse, the click generates an event known a mouse event. To capture the mouse event, Java gives the Programmer two interfaces known as MouseListener and MouseMotionListener.

Why two interfaces required for a simple mouse click?

To implement mouse handling in Java, the Designers separated mouse clicks (events) in two ways – mouse click done when the mouse is stable (not moving) and the mouse click done when the mouse is in motion (like in MS-Word, to select some text). The mouse click generated when the mouse is stable is handled by MouseListener interface and the other in motion is handled by MouseMotionListener interface.

1. A full program on MouseEvent handled by "MouseListener" with screen output refer: Java MouseListener

2. A full program on MouseEvent handled by "MouseMotionListener" with screen output refer: Java MouseMotionListener

3. Both "MouseListener" and "MouseMotionListener" in one program: Find X, Y Coordinates of Mouse Cursor Location in Java Applet

Leave a Comment

Your email address will not be published.