Java Reference
In-Depth Information
for (int x = 0; x < width; x += 5)
g.drawLine(x, y, width-x, height-y);
g.setColor(Color.YELLOW);
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
int strwid = fm.stringWidth(title);
g.drawString(title, (width-strwid)/2, height/2);
g.setColor(Color.RED);
strwid = fm.stringWidth(title);
g.drawString(title, (width-strwid)/2+3, height/2+3);
g.setColor(Color.GREEN);
g.fillOval(10, 10, 50, 50);
g.setColor(Color.BLUE);
g.fillRect(width-60, height-60, 50, 50);
}
}
before a GUI is presented. Splash screens are often presented to users to occupy their
attentionswhileapplicationsinitialize.(I'llhavemoretosayaboutsplashscreensinAp-
pendix C.)
There are several points of interest:
• Iprecreate
Dimension
,
Font
,and
String
objectstoavoidunneededobject
creation.
• I declare a Boolean variable named
invert
that (when true) results in the
background portion of the splash canvas being inverted.
• Ideclareaconstructorthatregistersamouselistenerwiththecanvas.Whenever
theuserclicksamousebuttonwhilethemousecursorisoverthiscomponent,
themouselistener's
void mouseClicked(MouseEvent me)
methodis
invoked.Thismethodtoggles
invert
andinvokes
Component
's
void re-
paint()
method, which tells AWT to invoke
paint()
as soon as possible.
• Iinvoke
Component
's
int getWidth()
and
int getHeight()
meth-
ods to obtain the canvas's width and height (in pixels).
• I invoke
fillRect()
to paint all the canvas's pixels using the current color
(black or white).