Java GUI Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for windows, is event driven. Event describes the change in state of any object. For Example : Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.
Components of Event Handling
Event handling has three main components,
- Events : An event is a change in state of an object.
- Events Source : Event source is an object that generates an event.
- Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.
How Events are handled?
A source generates an Event and send it to one or more listeners registered with the source. Once event is received by the listener, they process the event and then return. Events are supported by a number of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interface
|Event Classes||Description||Listener Interface|
|ActionEvent||generated when button is pressed, menu-item is selected, list-item is double clicked||ActionListener|
|MouseEvent||generated when mouse is dragged, moved,clicked,pressed or released and also when it enters or exit a component||MouseListener|
|KeyEvent||generated when input is received from keyboard||KeyListener|
|ItemEvent||generated when check-box or list item is clicked||ItemListener|
|TextEvent||generated when value of textarea or textfield is changed||TextListener|
|MouseWheelEvent||generated when mouse wheel is moved||MouseWheelListener|
|WindowEvent||generated when window is activated, deactivated, deiconified, iconified, opened or closed||WindowListener|
|ComponentEvent||generated when component is hidden, moved, resized or set visible||ComponentEventListener|
|ContainerEvent||generated when component is added or removed from container||ContainerListener|
|AdjustmentEvent||generated when scroll bar is manipulated||AdjustmentListener|
|FocusEvent||generated when component gains or loses keyboard focus||FocusListener|
Steps to handle events:
- Implement appropriate interface in the class.
- Register the component with the listener.
Example of Event Handling
public class Test extends Applet implements KeyListener
public void init()
public void keyPressed(KeyEvent k)
public void keyReleased(KeyEvent k)
public void keyTyped(KeyEvent k)
msg = msg+k.getKeyChar();
public void paint(Graphics g)
g.drawString(msg, 20, 40);
<applet code="Test" width=300, height=100>