O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Action Handling: Making Buttons Work

Problem

Your button doesn’t do anything when the user presses it.

Solution

Add an ActionListener to do the work.

Discussion

There are about half-dozen different types of event listeners. The most common is the ActionListener, used by push buttons, text fields, and certain other components to indicate that the user has performed a high-level action such as activating a push button or pressing Return in a text field. The paradigm (shown in Figure 13-3) is that you create a Listener object, register it with the event source (such as the push button) and wait. Later, when and if the user pushes the button, the button will call your Listener.

AWT listener relationships

Figure 13-3. AWT listener relationships

Here’s some simple code in which pushing a button causes the program to print a friendly message. This program is an applet (see Section 17.3), so it can use the showStatus( ) method to print its text:

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

/** Demonstrate use of Button */
public class ButtonDemo extends Applet implements ActionListener {
    Button b1;

    public ButtonDemo(  ) {
        add(b1 = new Button("A button"));
        b1.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event) {
        showStatus("Thanks for pushing my button!");
    }
}

This version does not use an inner class to handle the events, but does so itself by directly implementing the ActionListener ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required