Event Handling in Java with Example
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:
|ActionEvent||It is triggered whenever a user interface element is activated.
Example: Selected of a menu item
|ItemEvent||It is triggered at the selection or deselection of a list element.
|TextEvent||It is triggered when a text field is modified|
|WindowEvent||It is triggered whenever a window-related operation is performed.
Example: Closing or activating window
|KeyEvent||It 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 add<Type>Listener(<Type>Listener EveList)
Where Type is the name of the event & EveList is the corresponding listener object reference.
EventListener is the object that is referred by 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.
In AWT, all the events have corresponding event classes associated with them. Each of these classes is derived from one single superclass.
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.