MouseListener Java Example

MouseListener Java Example

The events of Java AWT can be divided into two broad categories – Semantic events and Low-level events. Semantic events are generated by software (GUI) components like frame, button etc and low-level events are generated by hardware components like mouse, keyboard etc.

You have seen so far the semantic events and their handling. Now let us go with low-level events. In this category three programs are given on MouseListener, MouseMotionListener and KeyListener. Now let us go with MouseListener.

Mouse events can be handled with MouseListener and MouseMotionListener. MouseListener handles the events when the mouse is stable and MouseMotionListener handles the events while the mouse is in motion.

When the mouse is stable, the mouse generates five types of actions represented by five abstract methods of MouseListener. The five actions are:

Action name MouseListener abstract method
Mouse key is pressed mousePressed()
Mouse key is released mouseReleased()
Mouse key is clicked mouseClicked()
Mouse is entering a frame mouseEntered()
Mouse is exiting a frame mouseExited()

All the above five methods take MouseEvent as parameter. When the mouse is entering or exiting a notepad file, a MS Word file or an Excel file, the mouse arrow changes a double-arrow symbol. These actions are represented by two methods – mouseEntered() and mouseExited().

The event generated by the Mouse is known as MouseEvent.

Following program illustrates the way of using the MouseListener with simple event-handling. For a bigger program refer MouseMotionListener.

MouseListener Java Example changing the background of the frame as per the action using MouseListener

Output screen on MouseListener Java Example

For the five types of actions of mouse (of course, when stable), the background color of the frame is changed and the action occurred is printed at the DOS prompt.

Leave a Reply

Your email address will not be published. Required fields are marked *