8.9. (Optional GUI) Containers and Layout Managers |
JFrame is a container that can hold other components. You can add GUI components such as labels, buttons, checkboxes, radio buttons , and combo boxes to a GUI container. Listing 8.9 gives an example that adds a button to a JFrame , as shown in Figure 8.16(a).
1 import javax.swing.*; 2 3 public class HoldComponents { 4 public static void main(String[] args) { 5 JFrame frame = new JFrame(); 6 7 // Add a button to frame 8 JButton jbtOK = new JButton( "OK" ); 9 frame.add(jbtOK); 10 11 frame.setTitle( "Window 1" ); 12 frame.setSize( 200 , 150 ); 13 frame.setLocation( 200 , 100 ); 14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15 frame.setVisible( true ); 16 } 17 } |
The program creates a JFrame in line 5 and a JButton in line 8. The button is added to the frame in line 9. Line 14 displays the frame. Each container uses a layout manager object to automatically arrange the components in a container. If you don't specify a layout manager, the default layout manager is used. In this case, the button is placed in the center of the frame and occupies the whole frame, as shown in Figure 8.16(a). To display a button in its preferred size as shown in Figure 8.16(b), use a FlowLayout manager as shown in Listing 8.10.
1 import javax.swing.*; 2 import java.awt.* ; 3 4 public class UseFlowLayout { 5 public static void main(String[] args) { 6 JFrame frame = new JFrame(); 7 8 // Set FlowLayout for the frame 9 FlowLayout layout = new FlowLayout(); 10 frame.setLayout(layout); 11 12 // Add a button to frame 13 JButton jbtOK = new JButton( "OK" ); 14 frame.add(jbtOK); 15 16 frame.setTitle( "Window 1" ); 17 frame.setSize( 200 , 150 ); 18 frame.setLocation( 200 , 100 ); 19 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 frame.setVisible( true ); 21 } 22 } |
The FlowLayout class is in the java.awt package, which is imported in line 2. A FlowLayout manager is created in line 9 and is set to the frame in line 10. The frame will use the FlowLayout to place the components. Listing 8.11 gives another example that adds two buttons in a frame of FlowLayout , as shown in Figure 8.17.
1 import javax.swing.*; 2 import java.awt.* ; 3 4 public class TwoButtons { 5 public static void main(String[] args) { 6 JFrame frame = new JFrame(); 7 8 // Set FlowLayout for the frame 9 FlowLayout layout = new FlowLayout(); 10 frame.setLayout(layout); 11 12 // Add two buttons to frame 13 JButton jbtOK = new JButton( "OK" ); 14 JButton jbtCancel = new JButton( "Cancel" ); 15 frame.add(jbtOK); 16 frame.add(jbtCancel); 17 18 frame.setTitle( "Window 1" ); 19 frame.setSize( 200 , 150 ); 20 frame.setLocation( 200 , 100 ); 21 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 frame.setVisible( true ); 23 } 24 } |