Signup/Sign In

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 ClassesDescriptionListener Interface
ActionEventgenerated when button is pressed, menu-item is selected, list-item is double clickedActionListener
MouseEventgenerated when mouse is dragged, moved,clicked,pressed or released and also when it enters or exit a componentMouseListener
KeyEventgenerated when input is received from keyboardKeyListener
ItemEventgenerated when check-box or list item is clickedItemListener
TextEventgenerated when value of textarea or textfield is changedTextListener
MouseWheelEventgenerated when mouse wheel is movedMouseWheelListener
WindowEventgenerated when window is activated, deactivated, deiconified, iconified, opened or closedWindowListener
ComponentEventgenerated when component is hidden, moved, resized or set visibleComponentEventListener
ContainerEventgenerated when component is added or removed from containerContainerListener
AdjustmentEventgenerated when scroll bar is manipulatedAdjustmentListener
FocusEventgenerated when component gains or loses keyboard focusFocusListener

Steps to handle events:

  1. Implement appropriate interface in the class.
  2. Register the component with the listener.

Example of Event Handling

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class Test extends Applet implements KeyListener
{
	String msg="";
	public void init()
	{
		addKeyListener(this);
	}
	public void keyPressed(KeyEvent k)
	{
		showStatus("KeyPressed");
	}
	public void keyReleased(KeyEvent k)
	{
		showStatus("KeyRealesed");
	}
	public void keyTyped(KeyEvent k)
	{
		msg = msg+k.getKeyChar();
		repaint();
	}
	public void paint(Graphics g)
	{
		g.drawString(msg, 20, 40);
	}
}

HTML code:

<applet code="Test" width=300, height=100>
</applet>

event handling example