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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.