Java Reference
In-Depth Information
Using Layout Managers in the Reservations() Constructor
Method
Recall that the Reservations class will contain a Reservations() constructor
method that defines what the Reservations object will be like when the object is
instantiated, or created. Typically, a constructor method of this sort is similar to
the init() method in an applet in that it adds components to the interface. In the
case of the Reservations() method, the layout manager, BorderLayout, will be
defined and the components will be added to Panels, each of which will use its
own layout manager. Figure 5-27 displays the code for the Reservations()
constructor method.
39
public Reservations ()
40
{
41
//set Layouts for frame and three panels
42
this .setLayout ( new BorderLayout ()) ;
43
roomPanel.setLayout ( new GridLayout ( 2,4,10,10 )) ;
44
buttonPanel.setLayout ( new FlowLayout ()) ;
45
inputPanel.setLayout ( new FlowLayout ()) ;
46
47
//add components to room panel
48
for ( int i=1; i<9; i++ )
49
{
50
roomDisplay [ i ] = new TextArea ( null ,3,5,3 ) ;
51
if ( i<6 )
52
roomDisplay [ i ] .setText ( "Room " + i + " Nonsmoking" ) ;
53
else
54
roomDisplay [ i ] .setText ( "Room " + i + " Smoking" ) ;
55
roomDisplay [ i ] .setEditable ( false ) ;
56
roomDisplay [ i ] .setBackground ( lightGreen ) ;
57
roomPanel.add ( roomDisplay [ i ]) ;
58
}
59
60
//add components to button panel
61
buttonPanel.add ( bookButton ) ;
62
63
//add components to input panel
64
inputPanel.add ( custNameLabel ) ;
65
inputPanel.add ( nameField ) ;
66
inputPanel.add ( custPhoneLabel ) ;
67
inputPanel.add ( phoneField ) ;
68
inputPanel.add ( numLabel ) ;
69
inputPanel.add ( numberOfGuests ) ;
70
for ( int i = 8; i<=20; i++ )
71
numberOfGuests.add ( String .valueOf ( i )) ;
72
inputPanel.add ( nonSmoking ) ;
73
inputPanel.add ( smoking ) ;
74
75
//add panels to frame
76
add ( buttonPanel, BorderLayout .SOUTH ) ;
77
add ( inputPanel, BorderLayout .CENTER ) ;
78
add ( roomPanel, BorderLayout .NORTH ) ;
79
80
bookButton.addActionListener ( this ) ;
81
FIGURE 5-27
As shown in line 42 of Figure 5-27, the layout for the entire Frame will be a
BorderLayout. The self-referential keyword, this, refers to the entire Reservations()
constructor method and thus sets the BorderLayout for the Frame. The Panels,
which are described in the storyboard in Figure 5-3 on page 310, use different
layout managers: roomPanel will use GridLayout to position the eight TextArea
components, and the buttonPanel and inputPanel will use FlowLayout.
Search WWH ::




Custom Search