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) {




Previous | Next | Top | Cafe au Lait

Copyright 1997, 2002 Elliotte Rusty Harold
Last Modified August 6, 2002