Eine gute Antwort könnte sein:

To a listener object. But our program does not have one, yet.

ActionListener

In analogy to window events, you would expect that there would be a ButtonAdapter class used as a base class for button listener objects. But there isn't. You need to define the complete class of a button listener from scratch.

A button listener class must implement the ActionListener interface. ActionListener is an interface (not a class) that contains the single method:

public void actionPerformed( ActionEvent evt) ;
The ActionEvent parameter it expects is an Event object that represents an event (a button click). It contains information that can be used in responding to the event. Since ActionListener is an interface, you use it with a class that will implement the actionPerformed() method. It is common to implement the interface in the same class that contains the button(s):

public class ButtonDemo2 extends JFrame implements ActionListener
{
  JButton bChange;

  // constructor for ButtonDemo2
  ButtonDemo2()
  {
    getContentPane().setLayout( new FlowLayout() );
    bChange = new JButton("Click Me!");
    getContentPane().add( bChange );
  }


  // listener method implemented for the ActionListener interface
  public void actionPerformed( ActionEvent evt)
  {
     . . . . . .
  }

  public static void main ( String[] args )
  {
    ButtonDemo2 frm = new ButtonDemo2();
      . . . . .
  }
}

This approach is different from that used with the WindowEvent of the previous chapter. There the WindowAdapter class was extended to define a separate class for the listener. Here the same class that holds the component is also the listener for it.

FRAGE 10:

Our class definition ButtonDemo2 says that it implements the ActionListener interface. What does this mean?

Inhaltsverzeichnis