Adding Buttons

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:

The two buttons are defined as below.

Adding Buttons

A skeleton of a constructor has been added to the program.

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

public class TwoButtons extends JFrame implements ActionListener
{

  JButton redButton;
  JButton grnButton;


  // constructor for TwoButtons
  public TwoButtons()                           
  {

    super( title );
    redButton = new JButton("Red");
    grnButton = new JButton("Green");

    . . . . more code will go here . . . . 
    
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   

  }

  . . . . more code will go here . . . . 

  public static void main ( String[] args )
  {
    TwoButtons demo  = new TwoButtons( "Click a Button") ;
    
    demo.setSize( 200, 150 );     
    demo.setVisible( true );      
  }
}

Now remember that GUI components need to be add()ed to the container.

QUESTION 6:

Decide where to use the add() method to add the buttons.