Eine gute Antwort könnte sein:

There is no listener for the button's events. If there is no listener for a particular type of event, then the program ignores events of that type.

Details

There is a listener for the frame's "close button," but not for the JButton. You can click the button, and generate an event, but no listener receives the event.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonDemo extends JFrame
{
  JButton bChange ;

  // constructor for ButtonDemo
  ButtonDemo()
  {
    // construct a Button
    bChange = new JButton("Click Me!");         3.

    // add the button to the JFrame
    getContentPane().add( bChange );            4.
                                                5.
  }

  public static void main ( String[] args )     1.
  {
    ButtonDemo frm = new ButtonDemo();          2.

    WindowQuitter wquit = new WindowQuitter();
    frm.addWindowListener( wquit );

    frm.setSize( 200, 150 );
    frm.setVisible( true );
  }
}

class WindowQuitter  extends WindowAdapter
{
  public void windowClosing( WindowEvent e )
  {
    System.exit( 0 );
  }
}
  1. The program starts running with main().
  2. main() constructs a ButtonDemo object.
  3. A JButton is constructed as part of the ButtonDemo object.
    • The words on the button will be "Click Me!"
    • The variable bChange refers to the JButton.
  4. The ButtonDemo constructor uses getContentPane().add( bChange ) to add the button to the frame.
  5. The default layout is used in adding the button to the frame.
    • The default is one big button in the center.

The ButtonDemo class does not need its own paint() method because everything in the frame is a component. The system will automatically paint all components in a container when it needs to. If special processing is needed, (as with drawString() in the previous chapter), then you need to override paint().

The program in the previous chapter did not define a constructor because it inherited the constructor from its parent class (JFrame), which is enough to do the job. When you add components to a container, you need to define a constructor for the frame.

FRAGE 5:

First let us look at the problem of the button that fills the frame. What size to you think would be better for the button? Where do you think the button should go?

Inhaltsverzeichnis