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


JLabel fatLabel    with    JTextField inFat

JLabel calLabel    with    JTextField inCal

JLabel perLabel    with    JTextField outPer

Adding Components to JPanels

The idea is to have five panels, one for each pair of label and text field, and a panel each for the heading and the do it button. The picture shows this grouping. (The lines around the panels do not appear in the actual GUI.)

GUI with panels

The add() method places components in a panel. The default layout manager, for JPanel is FlowLayout, so setLayout() does not need to be called.

public class percentFatPan 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!");
  JPanel hedPanel = new JPanel();
  JPanel fatPanel = new JPanel();
  JPanel calPanel = new JPanel();
  JPanel perPanel = new JPanel();   
  JPanel butPanel = new JPanel();   
  public percentFatPanel()   
    setTitle( "Calories from Fat" );
    outPer.setEditable( false );   
    setLayout( new FlowLayout() ); 

    hedPanel.add( heading );

    fatPanel.add(  );
    fatPanel.add(  );

    calPanel.add(  );
    calPanel.add(  );

    perPanel.add(  );
    perPanel.add(  );

    butPanel.add( doit );
   . . . . .

You need to say which container (which panel) gets each component.

whichPanel.add( objectRef )

means run the add() method of whichPanel to add the object to that panel.


Fill in the blanks by clicking the buttons.

At this point, the label and button components have been added to some panels, but the panels have not yet been added to the frame.