GUI Components of the Program

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:

Only the button needs to register a listener.

GUI Components of the Program

Fat Calculator GUI

The complete application (when we finish with it) is 80 lines long. All this to implement a one-line formula! For short applications, this is typical. But for longer applications the percentage of code for the GUI part is about 40%.

Let us build the interface part of the program. Look at the GUI on the right to determine what should go into the program. Click the buttons to see if you are correct.

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

public class PercentFat extends JFrame implements ActionListener
{
  JLabel heading    = new JLabel(" ");
  JLabel fatLabel   = new JLabel(" ");
  JLabel calLabel   = new JLabel(" ");
  JLabel perLabel   = new JLabel(" ");

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

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

  int calories ;    // input: total calories per serving
  int fatGrams ;    // input: grams of fat per serving
  double percent ;  // result: percent
    
  public PercentFat()  
  {  
    . . . . . . // components will be added 
    . . . . . . // to the frame here
  }

QUESTION 13:

(Review: ) What would happen if you used the class name Label instead of JLabel in the above?