go to previous page   go to home page   go to next page


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

JFrame with a JButton

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

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

class ButtonFrame extends JFrame
  JButton bChange ; // reference to the button object

  // constructor for ButtonFrame
  ButtonFrame(String title) 
    super( title );                     // invoke the JFrame constructor
    setLayout( new FlowLayout() );      // set the layout manager

    bChange = new JButton("Click Me!"); // construct a JButton
    add( bChange );                     // add the button to the JFrame
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   

public class ButtonDemo
  public static void main ( String[] args )
    ButtonFrame frm = new ButtonFrame("Button Demo");

    frm.setSize( 150, 75 );     
    frm.setVisible( true );   

new JButton("Click Me!") constructs a button object and puts the words "Click Me!" on it. The add() method of the frame puts the JButton into the frame.


How is the title "Button Demo" of the frame determined?