Learn how to handle Events using Java

In any interactive environment, the program should be able to respond to actions performed by the user. There actions can be Mouse click, Key Press or selection of a Menu Item. When the user initiates an action, the AWT generates an event and communicates it to event handlers. These event handlers can respond to the event appropriately.

Delegation Model

When an event is fired, it’s received by one or more listeners that act on that event.

The java.awt.AWTEvent is the root class of all AWT Event. AWTEvent is sub classed as ActionEvent, WindowEvent, ItemEvent, KeyEvent, MouseEvent etc. Event handling is achieved through the use of Listener Interfaces defined in the package java.awt.event. In java, we have a number of built in Interfaces as listeners for different types of event handling.

Basic steps to be followed to apply Events

Find out the Graphical User Component for which to apply the event. Implement the appropriate Interface or Interfaces corresponding to that component. Apply the methods involved in the Interface or Interfaces. Keep in mind that you can implement any number of Interfaces.

But, you should apply all the methods as mentioned in point 3 above. An alternative way is to apply Adapter classes. If you are extending Adapter classes, then you need to implement only the required methods. Each Adapter class contains the implementation of all of its methods by default.

List of Common Interfaces and its methods

Following are the important listeners and their usage syntaxes.

Action Listener

public void actionPerformed(ActionEvent e) {
statements
}

Item Listener

public void itemStateChanged(ItemEvent e) {
statements 
}

Mouse Listener

public void mouseClicked(MouseEvent e) {
statements 
}

In the same way, you should implement mousePressed(), mouseEntered(), mouseReleased() and mouseExited() methods. If you extend your class with MouseAdapter, then you need to apply only the required methods.

MouseMotion Listener

public void mouseMoved(MouseEvent e) { 
statements 
}

In the same way, you should implement mouseDragged() method. You can also extend MouseMotionAdapter class, so that you need to apply only the required methods.

Key Listener

public void keyPressed(KeyEvent e) { 
statements 
}

In the same way, you should implement keyReleased() and keyTyped() methods. As usual you can also extend KeyAdapter class.

Window Listener

public void windowClosing(WindowEvent e) { 
statements 
}

Other methods in this Interface are as follows

public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}

 

It’s better to use WindowAdapter class. This will simplify your coding and hence less time for debugging, if there are any errors.

Leave a Comment