Button Actions

Unlike labels, buttons do things when you press them. When the mouse is clicked on a Button, the Button fires an ActionEvent. To be ready to respond to this event you must register an ActionListener with the Button. For example,

     Button beep = new Button("Beep");    
     add(beep);  // add the button to the layout
     beep.addActionListener(myActionListener); // assign the button a listener
Here myActionListener is a reference to an object which implements the java.awt.event.ActionListener interface. This interface specifies a single method, actionPerformed():

public abstract void actionPerformed(ActionEvent e)

The ActionListener object does something as a result of the ActionEvent the button press fired. For example, the following class beeps when it gets an ActionEvent:

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

public class BeepAction implements ActionListener {

  public void actionPerformed(ActionEvent e) {

    Toolkit.getDefaultToolkit().beep();

  }

}

Previous | Next | Top
Last Modified November 5, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu