User interaction with the elements of graphical user interface(GUI) of a Java program leads to events. These elements could be a button, checkbox, radio button, menu, list, table, scrollbar, mouse, window etc.
Such elements are also known as source of an event and there is a specific class corresponding to each source and each event.
Some of the events could be -
A click on button, checkbox, radio button.
Selecting a menuitem or list item.
Clicking or movement of a mouse.
Entering or editing the data in a textfield.
Delegation Event Model
Java follows a Delegation Event Model to handle the such events. The two main components of this model are as follows -
Interaction with a source generates an event, which is an object of event class describing the current state of source.
A source must register the listener class that wishes to listen and respond to its event, by calling a method, which has a general form of -
public void addEventTypeListener(EventTypeListener el)
where, EventType could be replaced by the name of the type of event.
For example - A click on a source such as button raises to an event, which is an object of type ActionEvent class, hence a source button must call its method
addActionListener() to register any class that wishes to listen and respond to its button event of type ActionEvent.
The event is delegated to the registered listener classes. In order to listen and respond to events,
such registered listener class must implement EventTypeListener interface, where, EventType could be replaced by the name of the type of event.
For example - A class wishing to listen and respond to the a buttonclick event(which is an object of type ActionEvent), must implement ActionListener interface.
Interaction with elements of GUI raises events, which are nothing but objects of classes. EventObject
is the superclass of all the events. Let's see a table containing some different kinds of event classes
and the description of their events.
ActionEvent is generated when a source such as a button is clicked, an item in the list is double-clicked or when a menu item is selected.
ItemEvent is generated when a source such as a checkbox is clicked to check/uncheck it or when a list item is clicked.
KeyEvent is generated when a source such as a key on the keyboard pressed in a textfield or a textarea.
MouseEvent is generated when a source such a mouse is moved, dragged, enters/exits a specific window or when it's button is clicked/released.
TextEvent is generated when a data in textarea or textfield is changed.
AdjustmentEvent is generated when a scrollbar is dragged around.
WindowEvent is generated when a source such as a window is activated, minimized, brought up, deactivated and closed.
Let's see a table of some important event classes and their correspondinginterfaces that should be implemented
by classes in order to listen and respond to the events.