Friday, June 24, 2011

Basics of Event Handling

What is Event Handling?

Any operating environment that supports GUIs constantly monitors events such as keystrokes or mouse clicks. The operating environment reports these events to the programs that are running. Each program then decides what, if anything, to do in response to these events. For example, if you use the start menu and then click on My Computer, the OS identifies the fact that you want to view the details of your computer and opens up the Explorer window. The click on the icon is an event and the opening of the explorer window is how the OS handles the event.

As one would expect in an object-oriented language like Java, the information about the event is encapsulated in an event object. In Java, all event objects ultimately derive from the class java.util.EventObject. Of course, there are subclasses for each event type, such as ActionEvent and WindowEvent.
Different event sources can produce different kinds of events. For example, a button can send ActionEvent objects, whereas a window can send WindowEvent objects.

Below is how Events are handled in AWT:
• A listener object is an instance of a class that implements a special interface called a listener interface.
• An event source is an object that can register listener objects and send them event objects.
• The event source sends out event objects to all registered listeners when that event occurs.
• The listener objects will then use the information in the event object to determine their reaction to the event.

Look at the image below to understand the relationship between event sources and listeners.

Below is how you will specify a listener to a component, say a Button.
Now the listener object is notified whenever an “action event” occurs in the button. For buttons, as you rightly guessed, an action event is a button click.

To implement the ActionListener interface, the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter.
ActionListener listener = . . .;
JButton button = new JButton("Ok");
To implement the ActionListener interface, the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter.
class MyListener implements ActionListener{
    . . .
    public void actionPerformed(ActionEvent event)    {
        // code to handle button click goes here
        . . .

Whenever the user clicks the button, the JButton object creates an ActionEvent object and calls listener.actionPerformed(event), passing that event object. An event source such as a button can have multiple listeners. In that case, the button calls the actionPerformed methods of all listeners whenever the user clicks the button.

You can understand the event notification system by looking at the image below:

A Working Example:

Let us wrap up this chapter by looking at a full fledged example.

Let us say we want to have 3 buttons in our screen and 3 different actions must happen when the user clicks on them. For simplicity lets have the screen filled with 3 different colors when the user clicks on each of them.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestButtonActions
    public static void main(String[] args)
        EventQueue.invokeLater(new Runnable()
            public void run()
                MyTestFrame frame = new MyTestFrame();

 * A frame with a button panel
class MyTestFrame extends JFrame
    public MyTestFrame()
        setTitle("Button Action Test");

        // create buttons
        JButton redButton = new JButton("Red");
        JButton blueButton = new JButton("Blue");
        JButton greenButton = new JButton("Green");

        buttonPanel = new JPanel();

        // add buttons to panel

        // add panel to frame

        // create button actions
        HandleActions greenAction = new HandleActions(Color.GREEN);
        HandleActions blueAction = new HandleActions(Color.BLUE);
        HandleActions redAction = new HandleActions(Color.RED);

        // associate actions with buttons

     * An action listener that sets the panel's background color.
    private class HandleActions implements ActionListener
        public HandleActions(Color c)
            backgroundColor = c;

        public void actionPerformed(ActionEvent event)

        private Color backgroundColor;

    private JPanel buttonPanel;

    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;

If you compile and run this class your output will be like below:
On click of Red
On click of blue:
On click of green :

No comments:

Post a Comment