Java Reference
In-Depth Information
Display 18.16 paintComponent Demonstration (part 2 of 2)
R ESULTING GUI
The program in Display 18.17 has a private instance variable wink of type boolean .
When the value of wink is false , the paint method draws an ordinary happy face.
When the value of wink is true , the paint method draws the face the same except that
the left eye is just a straight line, which looks like the eye is closed. The variable wink is
initialized to false .
When the button labeled Click for a Wink is clicked, this sends an action event to
the method actionPerformed . The method actionPerformed then changes the value
of the variable wink to true and invokes the method repaint . This use of the method
repaint is new, so let's discuss it a bit.
Every JFrame (in fact, every Component and every Container ) has a method named
repaint . The method repaint will repaint the screen so that any changes to the
graphics being displayed will show on the screen. If you omit the invocation of
repaint from the method actionPerformed , then the variable wink will change to
true , but the screen will not change. Without an invocation of repaint , the face will
not change, because the method paint must be called again with the new value of
wink before the change takes effect. The method repaint does a few standard things
and, most importantly, will also invoke the method paint , which redraws the screen.
Be sure to note that you should invoke repaint and not paint .
Now we explain why, when wink has the value true , the method paint draws the
face with the left eye changed. The relevant part of the code is the following, which
draws the left eye:
repaint
if (wink)
g.drawLine(X_LEFT_EYE, Y_LEFT_EYE,
X_LEFT_EYE + EYE_WIDTH, Y_LEFT_EYE);
else
g.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT);
 
Search WWH ::




Custom Search