Action Handling: Making Buttons Work


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


Add an ActionListener to do the work.


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"));

    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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.