Java Reference
In-Depth Information
1 // Lay out all the objects
2 private void doTheLayout( )
3 {
4 JPanel topHalf = new JPanel( );
5 JPanel bottomHalf = new JPanel( );
6
7 // Lay out the top half
8 topHalf.setLayout( new FlowLayout( ) );
9 topHalf.add( theCanvas );
10 topHalf.add( new JLabel( "Shape" ) );
11 topHalf.add( theShape );
12 topHalf.add( theColor );
13 topHalf.add( new JLabel( "X coor" ) );
14 topHalf.add( theXCoor );
15 topHalf.add( new JLabel( "Y coor" ) );
16 topHalf.add( theYCoor );
17
18 // Lay out the bottom half
19 bottomHalf.setLayout( new FlowLayout( ) );
20 bottomHalf.add( smallPic );
21 bottomHalf.add( mediumPic );
22 bottomHalf.add( largePic );
23 bottomHalf.add( theFillBox );
24 bottomHalf.add( theDrawButton );
25 bottomHalf.add( theMessage );
26
27 // Now lay out GUI
28 setLayout( new BorderLayout( ) );
29 add( topHalf, "North" );
30 add( bottomHalf, "South" );
31 }
figure B.7
Code that lays out the
objects in Figure B.1
Lines 4 and 5 create the two JPanel objects topHalf and bottomHalf . Each
of the JPanel objects are then separately arranged using a FlowLayout . Notice
that the setLayout and add methods are applied to the appropriate JPanel .
Because the JPanel s are arranged with the FlowLayout , they may consume
more than one row if there is not enough horizontal real estate available.
This could cause a bad break between a JLabel and a JTextField . It is left as
an exercise for the reader to create additional JPanel s to ensure that any
breaks do not disconnect a JLabel and the component it labels. Once the
JPanel s are done, we use a BorderLayout to line them up. This is done at
lines 28 to 30. Notice also that the contents of both JPanel s are centered.
This is a result of the FlowLayout . To have the contents of the JPanel s left-
aligned, lines 8 and 19 would construct the FlowLayout with the additional
parameter FlowLayout.LEFT .
Search WWH ::




Custom Search