Nested Objects
Here is the new version of the program with the completed constructor.
public class percentFat extends Frame implements ActionListener
{
Label title = new Label("Percent of Calories from Fat");
Label fatLabel = new Label("Enter grams of fat: ");
Label calLabel = new Label("Enter total calories: ");
Label perLabel = new Label("Percent calories from fat: ");
TextField inFat = new TextField( 7 );
TextField inCal = new TextField( 7 );
TextField outPer = new TextField( 7 );
Button doit = new Button("Do It!");
Panel fatPanel = new Panel(); // fat input components
Panel calPanel = new Panel(); // calorie input components
Panel perPanel = new Panel(); // percent fat output components
percentFat() // constructor
{
setTitle("Calories from Fat");
setLayout( new FlowLayout() ); // choose the layout manager
fatPanel.add( fatLabel ); // add components to the panels
fatPanel.add( inFat );
calPanel.add( calLabel );
calPanel.add( inCal );
perPanel.add( perLabel );
perPanel.add( outPer);
add( title ); // add components to the frame
add( fatPanel );
add( calPanel );
add( perPanel );
add( doit );
outPer.setEditable( false );
doit.addActionListener( this );
}
|
Notice how objects are placed inside of objects:
- The percentFat Frame contains:
- The
title Label,
- The
fatPanel Panel, which contains:
- The
fatLabel Label
- The
inFat TextField
- The
calPanel Panel, which contains:
- The
calLabel Label
- The
inCal TextField
- The
perPanel Panel, which contains:
- The
perLabel Label
- The
outPer TextField
- The
doit Button.
The program took quite a bit of typing, but hopefully the ideas are clear enough.
Anyone who has come back from a department store with a shopping bag full
of bags full of purchases should see what is going on.
|