Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata