Previous
Index

Next


Objective 6, Writing listener code

Write code to implement listener classes and methods and in listener methods extract information from the event to determine the affected component, mouse position nature and time of the event. State the event classname for any specified event listener interface in the java.awt.event package.

Note on this objective

This objective can seem quite a tall order as there are many different graphical elements that generate different types of event. Thus a mouse will create one sort of event whereas a frame opening or closing will create an altogether different type of event. However much of what is required is memorisation so part of the task is just repetition until you are familiar with the classes, interfaces and event methods.

The listener event model

To write any useful GUI applications with Java you need to understand the listener classes and how to extract information from the events they process. The Java event handling system changed significantly between versions 1.0x and 1.1. In version 1.0x the event handling code concept was a little like plain C code for windows, i.e. fairly horrible. It required the creation of huge case statements where you would put in code to process a particular event according to parameters. This system is quite easy to understand for trivial examples but does not scale well for larger programs.

I get the impression that the only thing you need to know about the 1.1 exam for the 1.1 or Java2 exam is that the 1.1 approach is not backwardly compatible. In theory, code written for the 1.0x style of event handling should work OK in later versions of the JDK.

The JDK 1.1 event model

The Java 1.1 system involves using listener classes that are effectively "attached" to components to process specific events. This lends itself well for GUI builders to generate event handling code. If you examine the code generated by a GUI builders it can seem a little opaque, partly because it tends to involve inner classes created within methods. For the purpose of learning you can treat the event handling classes as top level classes.

One of the complicating factors for event handling is that it is based on Interfaces but is easiest to use with a series of classes known as the Adapter classes, that simply implement the event Interfaces. When you use an interface you need to implement all of its methods, thus direct use of the EventListener interface requires the creation of blank bodies for any unused event handling methods. By using the Adapter classes you only need to create the bodies of event handling methods you actually use.



The adapter classes allow you to use the Listener Interfaces without having to create a body for every method.



One of the most essential events to handle for a stand alone application is the simple ability to shut down an application in response to choosing the close option from the system menu. It may come as a surprise at first that this does not come as a default with a Java AWT Frame. If you create an application that extends Frame, but do not create code to handling closing, you will have to either kill it from the task manager or go back to the command line and hit control-c.

The equivalent Swing component to Frame, JFrame does process closing as a default action, but the certification does not cover the Swing components. As you must do this for the AWT Frame it is a good place to start covering the subject of event handling

The methods for WindowEvent handling are not as intuitive as some of the other Event methods. Thus it is not obvious at first if you need to respond to

windowClosed or windowClosing

In fact it is the windowClosing method method that needs to be processed. The simplest way to destroy the window is to use

System.exit(0);

Thus if you have an application with the main display of a frame you can give it the ability to close itself by creating a class that sub classes the WindowAdapter class and overrides the WindowClosing event with a new version that simply has the line

System.exit(0);

as the body of that method.

Here is an example of a simple application that shows a Frame that will respond by disappearing when you click the System/close menu choice. I

import java.awt.event.*;  //Make event handling available

import java.awt.*;
public class ShutHello extends Frame{
public static void main(String argv[]){
        ShutHello h = new ShutHello();
    }

    ShutHello(){
        Button b = new Button("ShutHello");
        //Create a new instance of the WindowCloser class

        WindowCloser wc = new WindowCloser();
        //Attach that listener to this program
        addWindowListener(wc);
        this.add(b);
        setSize(300,300);
        setVisible(true);
    }
}

class WindowCloser extends WindowAdapter{
        //override one of the methods in the Adapter class
        public void windowClosing(WindowEvent e){
        System.exit(0);
        }
}



The following example demonstrates how to use the interface classes directly rather than using the Adapter classes that wrap them and eliminate the need for blank method bodies.


The second half of the objective asks you to know the event class name for any event listener interface. The following table lists all of the Listener interfaces along with their methods. Do not be too put off by the apparent number of Interfaces and methods as they fit naturally into fairly intuitive groups based around things you would expect to be able to do with GUI components.

Thus the MouseListener interface offers methods for

clicked

pressed

released

entered

exited


If you compare this with event handlers in Visual Basic 5 the only significant area not covered is a set of methods for handling dragdrop events.

The name of the Event class passed to each method is fairly intuitive and based on the name of the Listener class. Thus all of the ActionListener methods take a parameter of ActionEvent, the ComponentListener methods take a ComponentEvent type, ContainerListener takes ComponentEvent etc etc etc.

There are 11 Listener Interfaces in all, but only 7 of them have multiple methods. As the point of the adapters is to remove the need to implement blank methods, Adapters classes are only implemented for these 7 Interfaces.

These are as follows

ComponentAdapter

ContainerAdapter

FocusAdapter

KeyAdapter

MouseAdapter

MouseMotionAdapter

WindowAdapter

The following table shows the full list of Event handling interfaces



Event Handling Interfaces

ActionListener

actionPerformed(ActionEvent)

addActionListener()

AdjustmentListener

adjustmentValueChanged(AdjustmentEvent)

addAdjustmentListener()

ComponentListener

componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)

addComponentListener()

ContainerListener

componentAdded(ContainerEvent)
componetRemoved(ContainerEvent)

addContainerListener()

FocusListener

focusGained(FocusEvent)
focusLost(FocusEvent)

addFocusListener()

ItemListener

itemStateChanged(ItemEvent)

addItemListener()

KeyListener

keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)

addKeyListener()

MouseListener

mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)

addMouseListener()

MouseMotionListener

mouseDragged(MouseEvent)
mouseMoved(MouseEvent)

addMouseMotionListener()

TextListener

textValueChanged(TextEvent)

addTextListener()

WindowListener

windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)

addWindowListener()




Questions

Question 1)

Which of the following statements are true?

1) For a given component events will be processed in the order that the listeners were added
2) Using the Adapter approach to event handling means creating blank method bodies for all event methods
3) A component may have multiple listeners associated with it
4) Listeners may be removed once added


Question 2)

Which of the following are correct event handling methods?


1) mousePressed(MouseEvent e){}
2) MousePressed(MouseClick e){}
3) functionKey(KeyPress k){}
4) componentAdded(ContainerEvent e){}


Question 3)

What will happen when you attempt to compile and run the following code?

import java.awt.*;
import java.awt.event.*;
public class MClick extends Frame implements MouseListener{
public static void main(String argv[]){
    MClick s = new MClick();
        }
        MClick(){
                this.addMouseListener(this);
        }

        public void mouseClicked(MouseEvent e){
                System.out.println(e.getWhen());
        }
}



1) Compile time error
2) Run time error
3) Compile and at runtime the date and time of each click will be output
4) Compile and at runtime a timestamp wil be output for each click


Question 4)

Which of the following statments are true about event handling?

1) The 1.1 Event model is fully backwardly compatible with the 1.0 event model
2) Code written for the 1.0x Event handling will run on 1.1 versions of the JVM
3) The 1.1 Event model is particularly suited for GUI building tools
4) The dragDrop event handler was added with the 1.1 version of event handling.

Answers

Answer 1)


3) A component may have multiple listeners associated with it
4) Listeners may be removed once added


Answer 2)

1) mousePressed(MouseEvent e){}
4) componentAdded(ContainerEvent e){}


Answer 3)


1) Compile time error

Because this code uses the Event listener, bodies must be created for each method in the Listener.
This code will cause errors warning that MClick is an abstract class.


Answer 4)


2) Code written for the 1.0x Event handling will run on 1.1 versions of the JVM
3) The 1.1 Event model is particularly suited for GUI building tools


Code written for the 1.1 event handling will not work with a 1.0x version of the JVM. I invented the name dragdrop method.


Other sources on this topic

The Sun Tutorial
http://java.sun.com/docs/books/tutorial/uiswing/events/intro.html

Jyothi Krishnan on this topic at
http://www.geocities.com/SiliconValley/Network/3693/obj_sec8.html#obj25

David Reilly
http://www.davidreilly.com/jcb/java107/java107.html








Previous
Index

Next