Java Reference
In-Depth Information
31 /** Main method */
32 public static void main(String[] args) {
33 TestPanels frame = new TestPanels();
34 frame.setTitle( "The Front View of a Microwave Oven" );
35 frame.setSize( 400 , 250 );
36 frame.setLocationRelativeTo( null ); // Center the frame
37 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
38 frame.setVisible( true );
39 }
40 }
The setLayout method is defined in java.awt.Container . Since JPanel is a subclass of
Container , you can use setLayout to set a new layout manager in the panel (line 8). Lines
7-8 can be replaced by JPanel p1 = new JPanel(new GridLayout(4, 3)) .
To achieve the desired layout, the program uses panel p1 of GridLayout to group the
number buttons, the Stop button, and the Start button, and panel p2 of BorderLayout to hold
a text field in the north and p1 in the center. The button representing the food is placed in the
center of the frame, and p2 is placed in the east of the frame.
The statement (lines 21-22)
p2.add( new JTextField( "Time to be displayed here" ),
BorderLayout.NORTH);
creates an instance of JTextField and adds it to p2 . JTextField is a GUI component that
can be used for user input as well as to display values.
Note
It is worthwhile to note that the Container class is the superclass for GUI component
classes, such as JButton . Every GUI component is a container. In theory, you could
use the setLayout method to set the layout in a button and add components to a but-
ton, because all the public methods in the Container class are inherited by JButton ,
but for practical reasons you should not use buttons as containers.
superclass Container
12.12
How do you create a panel with a specified layout manager?
Check
12.13
What is the default layout manager for a JPanel ? How do you add a component to a
JPanel ?
Point
12.14
Can you use the setTitle method in a panel? What is the purpose of using a panel?
12.15
Since a GUI component class such as JButton is a subclass of Container , can you
add components to a button?
12.7 The Color Class
Each GUI component has background and foreground colors. Colors are objects
created from the Color class.
You can set colors for GUI components by using the java.awt.Color class. Colors are made
of red, green, and blue components, each represented by an int value that describes its inten-
sity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model .
You can create a color using the following constructor:
Key
Point
public Color( int r, int g, int b);
in which r , g , and b specify a color by its red, green, and blue components. For example,
Color color = new Color( 128 , 100 , 100 );
Note
The arguments r , g , b are between 0 and 255 . If a value beyond this range is passed to
the argument, an IllegalArgumentException will occur.
IllegalArgumentException
 
 
Search WWH ::




Custom Search