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:
|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
public class MouseDemo extends Frame implements MouseListener
public MouseDemo( )
addMouseListener(this); // link the frame with ML
// override the 5 abstract methods of ML
public void mousePressed(MouseEvent e)
// do some action to distinguish from other methods
System.out.println("Mouse is Pressed");
public void mouseReleased(MouseEvent e)
System.out.println("Mouse is Released");
public void mouseClicked(MouseEvent e)
System.out.println("Mouse is Clicked");
public void mouseEntered(MouseEvent e)
System.out.println("Mouse is Entered");
public void mouseExited(MouseEvent e)
System.out.println("Mouse is Exited");
public static void main(String args)
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.