In Java (and most other programming environments), event handling is based on the observer design pattern. In this pattern, an object maintains one or more dependent objects and notifies them of any changes. In event handling, listeners or handlers are registered to a UI component and listen for events coming from the component. A listener contains a method which contains the code we want to run when an event happens.
When an event happens to a component, that event is passed on to all the listeners for that component; some of which might then respond to the event. When they have done this, they go back to listening.
The source component registers an event listener, which is responsible for handling the event. The event is fired by the component and an event object is passed to the listener.
The following are the steps we need to take to handle events:
1. Set up the GUI component.
2. Create a
Listener
object, for example, aSelectionListener
for handling button clicks.3. Associate the
Listener
object with the component we want to respond to, using theaddListener()
method, oraddSelectionListener()
which is recommended for aSelectionListener
.
That's basically all there is to event handling.
A simple form of event is the pressing of a button; this generates a ButtonEvent
, which we will listen for with a SelectionListener
. It is relatively easy to write the code to handle a button-press, so let's write one!
Button btn = new Button("Button Text"); SelectionListener<ButtonEvent> listener; listener = new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent evt) { String msg = evt.getButton().getText(); Info.display("Message", "Clicked - " + msg); } }; btn.addSelectionListener(listener);
Anonymous inner classes are unnamed inner classes (a class within a class), which help to simplify your code especially in event handling. The previous example can now be re-written as follows:
Button btn = new Button("Button Text", new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent evt) { String msg = evt.getButton().getText(); Info.display("Message", "Clicked - " + msg); } });
The use of anonymous inner classes in event handlers is quite common. However, for code clarity, these handlers should be very short code snippets.