Java Reference
In-Depth Information
10
}
fixGUI(Frame)
isinvokedwithareferencetothe
TempVerter
framewindow
(
TempVerter.this
provides that reference). It first invokes
f.getComponents()[0]
toobtainthepanelthatwasaddedtotheframewindow.
pnl
/
pnlLayout
contains three
Panel
instances (recall
pnlTemp
). The second
line fetches the first of these instances and assigns its reference to
pnlRow
. The third
lineextractstheDegreeslabelcomponent,whichisthefirstcomponent(atposition0)
within this panel.
Thefourthlinefetchesthesecond
Panel
instancethatcontainstheResultlabeland
its associated textfield. The fifth line extracts this label.
The sixth line invokes
getPreferredSize()
on the Result label, and then in-
vokes
Component
's
void setPreferredSize(Dimension preferredS-
ize)
method with this preferred size to shrink the width of the Degrees label so that
both textfields are left-aligned.
The seventh line fetches the third
Panel
instance, which contains the two buttons,
theeighthandninthlinesextractthesebuttons,andthetenthlinesetsthepreferredsize
of the Convert to Celsius button to that of the wider Convert to Fahrenheit button.
Introducing
fixGUI(Frame)
into
TempVerter
is only part of the solution. We
mustalsocallthismethod,andtheappropriateplacetodosoisbetweentheframewin-
dow's
pack()
and
setVisible()
method calls.
fixGUI()
mustbecalledafter
pack()
becausethepreferredsizesarenotknown
until after
pack()
has been called. This method must be called before
setVis-
ible()
becauseitchangespreferredsizes.
setVisible()
canaccommodatethese
changeswhentheyaremadebeforethismethodiscalled.However,whentheyaremade
after calling
setVisible()
,
pack()
will have to be called a second time.
Note
Although
fixGUI()
isconvenientfortrivialapplications,youwon'tneedto
useitafterlearningmoreaboutlayoutmanagement(whichunfortunatelyisbeyondthe
scope of this chapter).
fixGUI()
can be tedious to code, and you need to revise it
whenever you change the GUI.Graphics, Colors, and Fonts
The
Component
class declares a
void paint(Graphics g)
method to paint
a component. Painting occurs when a component is first shown or when it has been
damaged(bybeingpartlyorcompletelyobscuredbyanothercomponent)andisbeing
reshown.