Eine gute Antwort könnte sein:

Yes. This means that a JButton can contain other components. This is sometimes used to put a picture on a button. Ordinary AWT buttons (class Button) can't do this.

Example Program with a Button

Here is an example program that adds a button to a frame.

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

public class ButtonDemo extends JFrame
{
  JButton bChange ; // reference to the button object

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

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

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

    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 );
  }
}

To construct a JButton object, use new. Then add the button to the frame's content pane. The content pane is a container that represents the main rectangle of the frame. The add method of a content pane puts a JButton into the frame.

To get a reference to the content pane, use the getContentPane() method of the frame.

The JButton now will be displayed when the frame is displayed, and will move in and out when the user clicks on it. Clicking on the button generates events, but so far the program does not respond to those events.

FRAGE 3:

Does the WindowQuitter object listen to clicks on the JButton?

Inhaltsverzeichnis