Action Commands

The setActionCommand() and getActionCommand() methods modify the command string sent along with the ActionEvent. By default this is the label of the button, but it can be changed. For instance, you could use this as a way to pass the number of times the BeepApplet should beep
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class BeepFiveApplet extends Applet  {
   public void init () {
     // Construct the button
     Button beep = new Button("Beep");

     // add the button to the layout

     // specify that action events sent by this
     // button should be handled by the applet itself
     beep.addActionListener(new MultiBeepAction());

class MultiBeepAction implements ActionListener {

  public void actionPerformed(ActionEvent ae) {

    int n;
    try {
      n = Integer.parseInt(ae.getActionCommand());
    catch (NumberFormatException e) {
      n = 1;
    Toolkit tk = Toolkit.getDefaultToolkit();
    for (int i = 0; i < n; i++) tk.beep();



Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
Last Modified March 23, 1998