HOW EVENT HANDLING WORKS

 

 

From the previous example we are left with  2 questions.

 

  1. How did the event handler get registered?
  2. How does the GUI component know to call actionPerformed as opposed to some other even handling method?

 

 

The first question is answered in the code when we call the method on the text fields addActionListener .

 

 

How this works is that every JComponent has an object of class EventListenerList called listenerList as an instance variable. All registered listeners are stored in the listener list. When the addActionListener call is executed a new entry is placed in the listenerList for the JTextField indicating both the reference to the listener object and the type of listener.(In this case the ActionListener).

 

The type is important in answering the second question – how does the GUI component know to call actionPerformed rather than another event handling method? Every JComponent actually supports several different even types, including mouse events, key events and others. When and even occurs, the event is dispatched only to the event listeners of the appropriate type. The dispatching of an event is simply calling the event handling method for each registered listener for that event type.

 

 

Each event type had a corresponding event-listener interface some of these are:

 

ActionEvents are handled by ActionListeners

MouseEvents are handled by MouseListeners

KeyEvents are handled by KeyListeners

 

When an event is generated by a user interaction with a component, the component is handed a unique event ID specifying the event type that occurred. The GUI component uses the event ID to decide the type of listener to which the event should be dispatched and the method to call. In the case of an ActionEvent, the event is dispatched to every registered ActionListener’s actionPerformed method (the only method in interface ActionListener). Others such as the MouseEvent has seven different event handling methods and the Even ID determines which of these will be called.