Event Handling in Java with Example

Event Handling in Java:

Event Handling is a mechanism that is used to handle events generated by applets. An event could be the occurrence of any activity such as a mouse click or keypress. In Java, events are regarded as method calls with a certain task performed against the occurrence of each event. Some of the Event-handling methods in Applet are given as follows:




Key Events Description
ActionEventIt is triggered whenever a user interface element is activated.
Example: Selected of a menu item
ItemEventIt is triggered at the selection or deselection of a list element.
Example: Checkbox
TextEventIt is triggered when a text field is modified
WindowEventIt is triggered whenever a window-related operation is performed.
Example: Closing or activating window
KeyEventIt is triggered whenever a key is pressed on the keyboard.

Each event is associated with an event source and an event handler.

Event source: It refers to the object that is responsible for generating an event.

public void addListener(Listener EveList)

Where Type is the name of the event & EveList is the corresponding listener object reference.

EventListener:

EventListener is the object that is referred to by the event source at the time of occurrence of an event. These methods are implemented from the corresponding listener interface contained in the java.awt.event package.

Event Classes:

In AWT, all the events have corresponding event classes associated with them. Each of these classes is derived from one single superclass.

Example:
EventObject: It is contained in the java.util package. The EventObject class contains two important methods for Event handling:

getSource(): It simply returns the event source.
toString(): It returns a string containing information about the event source.