Event Handling Event and Listener (Java Event Handling) Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling . Types of Event The events can be broadly classified into two categories: Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc . Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.
Event Handling Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model . The Delegation Event Model has the following key participants namely: Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object. Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns .
L 2.1 Event Listeners A listener is an object that is notified when an event occurs. Event has two major requirements. It must have been registered with one or more sources to receive notifications about specific types of events. 2. It must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event . For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.
Steps to perform Event Handling Register the component with the Listener For registering the component with the Listener, many classes provide the registration methods. For example: Button public void addActionListener ( ActionListener a){} MenuItem public void addActionListener ( ActionListener a){} TextField public void addActionListener ( ActionListener a){} public void addTextListener ( TextListener a){} TextArea public void addTextListener ( TextListener a){} Checkbox public void addItemListener ( ItemListener a){} Choice public void addItemListener ( ItemListener a){} List public void addActionListener ( ActionListener a ){}
public void addItemListener ( ItemListener a ){} For the understanding purpose, we will be looking at the ActionListener as it is the most commonly used event listener and see how exactly it handles the events . // Java event handling by implementing ActionListener import java.awt .*; import java.awt.event .*; class EventHandle extends Frame implements ActionListener { TextField textField ; EventHandle () { textField = new TextField (); textField.setBounds (60,50,170,20); Button button = new Button("Quote"); button.setBounds (90,140,75,40); //1 button.addActionListener (this); add(button); add( textField ); setSize (250,250); setLayout (null); setVisible (true); }
//2 public void actionPerformed ( ActionEvent e){ textField.setText ("Keep Learning"); } public static void main(String args []){ new EventHandle (); } } (1) (2)
Image 1 shows the output of our code when the state of the button was unclicked. Image 2 shows the output after the button is pressed . Now , look at the code I’ve divided it into 2 important parts. Int the first part we are registering our button object with the ActionListener . This is done by calling the addActionListener ( ) method and passing current instance using ‘this’ keyword . Once we have registered our button with the ActionListener now we need to override the actionPerformed ( ) method which takes an object of class ActionEvent . Delegation Event Model We know about Source, Listener, and Event. Now let’s look at the model which joins these 3 entities and make them work in sync. The delegation event model is used to accomplish the task. It consists of 2 components Source and listener. As soon as the source generates an event it is noticed by the listener and it handles the event at hand. For this action to happen the component or the source should be registered with the listener so that it can be notified when an event occurs. The specialty of delegation Event Model is that the GUI component passes the event processing part to a completely separate set of code.
Event Methods to ‘Override’ EvenListener ActionEvent - Events generated from buttons, menu items, etc. actionPerformed(ActionEvent e) ActionListener KeyEvent- Events generaated when input is received from the keyboard. keyPressed ( KeyEvent ke ) keyTyped ( KeyEvent ke ) keyReleased ( KeyEvent ke ) KeyListener ItemEvent- Events generated from List, Radio Button, etc. itemStateChanged(ItemEvent ie ) ItemListener MouseEvent – Event generated by the mouse mouseMoved ( MouseEvent me) mouseDragged ( MouseEvent me) MouseMotionListener List Of Listeners
Delegation Event Model We know about Source, Listener, and Event. Now let’s look at the model which joins these 3 entities and make them work in sync. The delegation event model is used to accomplish the task. It consists of 2 components Source and listener. As soon as the source generates an event it is noticed by the listener and it handles the event at hand. For this action to happen the component or the source should be registered with the listener so that it can be notified when an event occurs . The specialty of delegation Event Model is that the GUI component passes the event processing part to a completely separate set of code.
Java MouseListener Interface The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent . The MouseListener interface is found in java.awt.event package. It has five methods. Methods of MouseListener interface The signature of 5 methods found in MouseListener interface are given below: public abstract void mouseClicked ( MouseEvent e); public abstract void mouseEntered ( MouseEvent e); public abstract void mouseExited ( MouseEvent e); public abstract void mousePressed ( MouseEvent e); public abstract void mouseReleased ( MouseEvent e);
import java.awt .*; import java.awt.event .*; public class MouseListenerExample extends Frame implements MouseListener { Label l; M o u s e L i s t e n e rE x a m p l e () { a dd M o u s e L i s t e n e r ( t h i s ) ; l= new Label(); l.setBounds ( 20 , 50 , 100 , 20 ); add(l); setSize ( 300 , 300 ); setLayout ( null ); setVisible ( true ); } public void mouseClicked ( MouseEvent e) { l.setText ( "Mouse Clicked" ); } public void mouseEntered ( MouseEvent e) { l.setText ( "Mouse Entered" ); } public void mouseExited ( MouseEvent e) { l.setText ( "Mouse Exited" ); } public void mousePressed ( MouseEvent e) { l.setText ( "Mouse Pressed" ); } public void mouseReleased ( MouseEvent e) { l.setText ( "Mouse Released" ); }
public static void main(String[] args ) { new MouseListenerExample (); } }
L 3.3 Adapter classes Java provides a special feature, called an adapter class , that can simplify the creation of event handlers. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.
L 3.4 adapter classes in java.awt.event are . Adapter Class Listener Interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener
L 3.5 Inner classes Inner classes, which allow one class to be defined within another. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. An inner class is fully within the scope of its enclosing class. an inner class has access to all of the members of its enclosing class, but the reverse is not true. Members of the inner class are known only within the scope of the inner class and may not be used by the outer class