Example Program with a Button

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

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.

QUESTION 3:

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