Home | Articles

Event Handling Model and Listener Interfaces

The new event handling model provides event listener interfaces and adapter classes for setting up event listening functionality in your programs. Whether you choose to implement the interfaces, use the adapter classes, or combine interface implementations with adapter classes depends on your application requirements.

Event Listener Interfaces

In the class declaration, declare the event listener interfaces for the events you need. With this approach, you have to implement all the interface methods for the interfaces you declare. If an event listener interface has methods not used by the program, consider using the corresponding adapter class instead.

The following code makes the LayoutExample class an action listener by implementing the ActionListener interface. An action listener responds with its actionPerformed() implementation when the end user clicks a button, double clicks a list item, makes a menu selection, or presses Return in a text field. The actionPerfomed() implementation handles all such events for components you explicitly add as event listeners (see below).


  import java.awt.*;
  import java.awt.event.*;

  public class LayoutExample extends Frame 
    implements ActionListener {

  public void actionPerformed(ActionEvent event){
       //Event handling implementation
     }
  }

Adding Components as Event Listeners

You have to add components as event listeners. The component classes have the appropriate add methods for this purpose. For example, Button, List, MenuItem, and TextField objects have an addActionListener method, and all Container objects have addComponentListener, addFocusListener, addInputMethodListener, addKeyListener, addMouseListener, and addMouseMotionListener methods.

The following excerpted code shows how to add a button as an action listener. Click here for the complete program.


  import java.awt.*;
  import java.awt.event.*;

  public class LayoutExample extends Frame
    implements ActionListener {

     Panel p1;
     Button border;

     public LayoutExample(){

  //Create a panel and a button
       p1 = new Panel();
       border = new Button("Border Layout");

  //Add the panel to the frame
       add(p1);

  //Add the button to the panel
       p1.add(border); 

  //Make the button an action listener
       border.addActionListener(this);
     }

  //Set up actionPerformed method to 
  //catch button event

  public void actionPerformed(ActionEvent event){
    Object source = event.getSource();

       if(source == border){
	 //Event handler implementation 
       }
     } 
  }

Because LayoutExample is a subclass of java.awt.Frame, you can add the window closing behavior by implementing the java.awt.Frame.addWindowListener() method as shown in the next code segment.

If you extend the class from applet instead of frame, there is no need to add a window listener. In fact, the applet class has no methods for adding window listeners because window listening functionality is built in.


  import java.awt.*;
  import java.awt.event.*;

  public class LayoutExample extends Frame
    implements ActionListener {
     Panel p1;
     Button border;

     public LayoutExample(){
       p1 = new Panel();
       border = new Button("Border Layout");
       add(p1);
       p1.add(border);
       border.addActionListener(this);
     }

  //Provide window closing implementation
     addWindowListener(new WindowAdapter(){
       public void windowClosing(WindowEvent event){
         system.exit(0);
       }
     });

     public void actionPerformed(ActionEvent event){
       Object source = event.getSource();

       if(source == border){
         //Event handler implementation
       }
     }
  }

Source Code

The following source files contain the JDK 1.0 and 1.1 versions of the application code for the demonstration application used in the Exploring the AWT Layout Managers article. The only difference between the two versions is how event handling is coded. The JDK 1.1 applet source code is the applet version of the JDK 1.1 source code. The only differences between the application and applet versions are that applets do not have main methods and the window closing behavior is built in.

JDK 1.0

JDK 1.1

JDK 1.1 Applet

The following source files contain the JDK 1.1 application with the event handling code in a separate non-component class.

Initial GUI, and
Event Handling Code

Using Adapter Classes

Many event listener interfaces contain more than one method. For example, the MouseListener interface, which responds to end user mouse or other similar input device actions, has five methods: mousePressed(), mouseReleased(), mouseEntered(), mouseExited(), and mouseClicked().

If you implement the MouseListener interface, you have to implement all five methods even if you only need one. To get around having a lot of empty method implementations cluttering your code, you can extend MouseAdapter and implement only the methods you need:


  import java.awt.*;
  import java.awt.event.*;

  public class MouseExample extends MouseAdapter {

     aComponent.addMouseListener(this);

     public void mouseClicked(MouseEvent event) {
                //Event handling implementation
        }
  }

Using Inner Classes

Adapter classes have to be extended to be used, and sometimes your class already extends another class. The Java language does not allow multiple inheritance, so in this case you have to use the adapter class as an inner class. While a class can extend only one class, it can implement as many interfaces and use as many inner classes as it needs.

The example below shows the MouseExample class extending Frame and using AMouseAdapter as an inner class that extends MouseAdapter.


  import java.awt.*;
  import java.awt.event.*;

  public class MouseExample extends Frame {

    aComponent.addMouseListener(
      new AMouseAdapter());

    class AMouseAdapter extends MouseAdapter{

      public void mouseClicked(MouseEvent event){
        //Event handling implementation
          }
    }
  }

The following applet code taken from The Java Tutorial: Object Oriented Programming for the Internet. uses an inner class to implement the MouseAdapter class.


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class AdapterSpot extends Applet
{
   private Point clickPoint = null
   private static final int RADIUS = 7;

   public void init(){
     addMouseListener(new MyMouseAdapter());
   }

   public void paint(Graphics graphic){
     g.drawRect(0, 0, getSize().width - 1,
                      getSize().height =1);
     if(clickPoint != null)
        graphic.fillOval(clickPoint.x-RADIUS,
                         clickPoint.y-RADIUS,
                         RADIUS*2, RADIUS*2);
   }

   class MyMouseAdapter extends MouseAdapter{
     public void mousePressed(Mouse Event event){
        clickPoint = event.getPoint();
        repaint();
     }
   }
}

Conclusion

The JDK 1.1 event model is more flexible, more powerful, and easier to use than the JDK 1.0 event model. Upgrading your JDK 1.0 code makes it possible for you to take advantage of new features and Swing.

Once you convert to the new event model, you can convert your Abstract Window Toolkit (AWT) components to Swing components.

© 1994-2005 Sun Microsystems, Inc.