Adding Components

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:

Class names like Label, Button, and TextField exist and are valid classes from the AWT (not Swing). A completed program would compile and run, but might not work as you expect.

Adding Components

Fat Calculator GUI

 

Use FlowLayout for the layout manager. It puts components into the content pane in the order they are added. Now the GUI components need to be added to the frame in the correct order. (Caution: this is not necessarily the same order in which they are declared.)

To put a label to the left of a component, first add the label, then add the component. But if the frame is too small, the component might be placed in the next row! There are better ways to do this which will be discussed later.



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

public class PercentFat extends JFrame implements ActionListener
{
  JLabel heading   = new JLabel("Percent of Calories from Fat");
  JLabel fatLabel  = new JLabel("Enter grams of fat:   ");
  JLabel calLabel  = new JLabel("Enter total calories: ");
  JLabel perLabel  = new JLabel("Percent calories from fat: ");

  JTextField inFat  = new JTextField( 7 );
  JTextField inCal  = new JTextField( 7 );
  JTextField outPer = new JTextField( 7 );

  JButton    doit   = new JButton("Do It!");

  double calories ;   // input: total calories per serving
  doublet fatGrams ;  // input: grams of fat per serving
  double percent;     // result: percent of calories from fat

  public PercentFat()
  {  
    setLayout( ) ; 

    add(   ) ;
    add(   ) ;
    add(   ) ;
    add(   ) ;
    add(   ) ;
    add(   ) ;
    add(   ) ;
    outPer.setEditable( false );

    add(   ) ;
    
    doit.addActionListener( this );
    
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }

   . . . . .

QUESTION 14:

Has an ActionListener been registered?