Java Reference
In-Depth Information
Listing11-18
combinesSwing/AbstractWindowToolkitcodeforcreatingauserin-
terfacewithSAAJcodeforcommunicatingwiththeRomanNumeralsConversionweb
service.
Theuserinterfaceconsistsofapairoftextfieldsandapairofbuttons.Oneofthese
textfieldsisusedtoentertheRomannumeralsorbase-10integerdigitsofthevalueto
be converted. The other textfield displays the conversion result. Click one of the but-
tonstoconvertfromRomannumeralstointegerdigits;clicktheotherbuttontoachieve
the opposite conversion. In response to a button click, either the
String toIn-
teger(String input)
method or the
String toRoman(String input)
method is called to perform the conversion.
BecauseIdiscussthebasicsofJava'suserinterfaceAPIsextensivelyin
Chapter7
,I
won't revisit them here. Instead, consider the
GPanel
(Gradient Panel) class.
Iintroduced
GPanel
sothatIcouldgenerateacolorfulbackgroundfortheapplica-
tion'swindow.Someuserinterfacedesignersmightdisagreewithpaintingapink-to-or-
ange
gradient
(gradualchangeincolorfromaninitialcolortoafinalcolor)asawindow
background, but I like it. (After all, beauty is in the eye of the beholder.)
GPanel
extends
JPanel
todescribeacustompanelwhosesurfaceispaintedwith
agradientwheneveritsinherited
void paintComponent(Graphics g)
method
iscalled.Thishappenswhenthewindowisfirstdisplayed,andwhenthewindowisre-
stored after being minimized (at least on Windows platforms).
GPanel
uses the
java.awt.GradientPaint
class to paint the gradient. (I
could have used the Java 6-introduced
java.awt.LinearGradientPaint
class
instead,butflippedacoinandendedupusing
GradientPaint
.)Thefirsttwoargu-
mentspassedtothisclass'sconstructoridentifytheupper-leftcorner(inuserspace—see
specifiesthecoloratthetopofthegradient,thefourthandfifthargumentsidentifythe
rectangular area's lower-right corner, and the final argument identifies the color at the
bottom of the gradient.
Note
The instantiation of
GradientPaint
demonstrates
lazy initialization
, in
which an object is not created until the first time it is needed. Check out Wikipedia's
“Lazy initialization” entry (
http://en.wikipedia.org/wiki/
Lazy_initialization
)
for more information about this pattern.
Ideally, the user interface's components appear over a gradient background, and not
oversomeintermediatebackground.However,becausetheuserinterfaceiscreatedfrom
panelsofcomponentsaddedtothegradientpanel,thegradientpanel'ssurfacewillnot
show through these “upper” panels unless they are made transparent, by calling their