Java Reference
In-Depth Information
figure B.5
Five buttons arranged
using BorderLayout
shown in Figure B.6. Observe that we use the typical idiom of adding into a
lightweight JPanel and then adding the JPanel into the top-level JFrame 's con-
tent pane. Typically, some of the five locations may be unused. Also, the com-
ponent placed in a location is typically a JPanel that contains other
components using some other layout.
As an example, the code in Figure B.7 shows how the objects in Fig-
ure B.1 are arranged. Here, we have two rows, but we want to ensure that
the check boxes, buttons, and output text field are placed below the rest of
the GUI. The idea is to create a JPanel that stores the items that should be
in the top half and another JPanel that stores the items in the bottom half.
These two JPanel s can be placed on top of each other by arranging them
using a BorderLayout .
figure B.6
Code that illustrates
BorderLayout
1 import java.awt.*;
2 import javax.swing.*;
3
4 // Generate Figure B.5
5 public class BorderTest extends JFrame
6 {
7 public static void main( String [ ] args )
8 {
9 JFrame f = new BorderTest( );
10 JPanel p = new JPanel( );
11
12 p.setLayout( new BorderLayout( ) );
13 p.add( new JButton( "North" ), "North" );
14 p.add( new JButton( "East" ), "East" );
15 p.add( new JButton( "South" ), "South" );
16 p.add( new JButton( "West" ), "West" );
17 p.add( new JButton( "Center" ), "Center" );
18
19 Container c = f.getContentPane( );
20 c.add( p );
21 f.pack( ); // Resize frame to minimum size
22 f.setVisible( true ); // Display the frame
23 }
24 }
Search WWH ::




Custom Search