Java Reference
In-Depth Information
Figure 7-6.
An even nicer looking GUI is achieved by aligning and resizing compon-
ents.
The labels are left-aligned by executing
((FlowLayout) pn-
lTemp.getLayout()).setAlignment(FlowLayout.LEFT);
on each of
thetwo
pnlTemp
variablesthatstoresalabelandatextfield.Thismethodcallobtains
pnlTemp
's default flow layout manager and calls
FlowLayout
's
void setA-
lignment(int alignment)
method on this instance to align the panel's com-
ponents to the left edge of the container (thanks to
FlowLayout
's
LEFT
con-
stant)—
FlowLayout
leavesadefault5-pixelgaponeachsideofthepanelthatserves
as a margin.
However,thetextfieldsarenotleftaligned.Toalignthem,weneedtosetthepreferred
sizeofthewiderDegreeslabeltothepreferredsizeofthenarrowerResultlabel.Sim-
ilarly,weneedtosetthepreferredsizeoftheConverttoCelsiusbuttontothepreferred
size of the Convert to Fahrenheit button so that they have equal widths.
These tasks can be accomplished in part by introducing the following
void
fixGUI(Frame)
class method into the
TempVerter
class:
static void fixGUI(Frame f)
{
Panel pnl = (Panel) f.getComponents()[0]; // 1
Panel pnlRow = (Panel) pnl.getComponents()[0]; // 2
Label l1 = (Label) pnlRow.getComponents()[0]; // 3
pnlRow = (Panel) pnl.getComponents()[1]; // 4
Label l2 = (Label) pnlRow.getComponents()[0]; // 5
l1.setPreferredSize(l2.getPreferredSize()); // 6
pnlRow = (Panel) pnl.getComponents()[2]; // 7
Button btnToC = (Button) pnlRow.getComponents()[0]; // 8
Button btnToF = (Button) pnlRow.getComponents()[1]; // 9
btnToC.setPreferredSize(btnToF.getPreferredSize());
//