Java Reference
In-Depth Information
The
repaint
and
paint
Methods
When you change the graphic's contents in a window and want to update the window so
that the new contents show on the screen, do not call
paint
; call
repaint
. The
repaint
method takes care of some overhead and then calls the
paint
method. Normally, you do
not define
repaint
. As long as you define the
paint
method correctly, the
repaint
method should work correctly. Note that you often define
paint
, but you normally do not
call it. On the other hand, normally you do not define
repaint
, but you do sometimes call it.
Some More Details on Updating a GUI
★
Most of the changes to a GUI windowing system that we have seen are updated
automatically so that they are visible on the screen. This is done by an object known
as the
repaint manager
. The repaint manager works automatically, and you need
not even be aware of its presence. However, there are a few updates that the repaint
manager will not do for you. You have already learned that you need an invocation of
repaint
when your GUI changes the figure drawn in the
JFrame
as in Display 18.17 .
Two other updating methods that you will often see when looking at Swing code
are
validate
and
pack
.
Every container class has the method
validate
, which has no arguments. An invocation
of
validate
causes the container to lay out its components again. An invocation of
validate
is a kind of “update” action that makes changes in the components actually
happen on the screen. Many simple changes that are made to a Swing GUI, such as
changing color or changing the text in a text field, happen automatically. Other changes,
such as some kinds of addition of components or changes in visibility, may require an
invocation of
validate
or some other “update” method. Sometimes it is difficult to
decide whether an invocation of
validate
is necessary. When in doubt, include an
invocation of
validate
. Although invoking
validate
when it is not needed can make
your program a little less efficient, it will have no other ill effects on your GUI.
The method
pack
causes the window to be resized, usually to a smaller size, but
more precisely to an approximation of a size known as the
preferred size
. (Yes, you can
change the preferred size, but we do not have room to cover all of the Swing library in
these few chapters .)
We do not have enough space in this topic to go into all the details of how a GUI
is updated on the screen, but these few remarks may make some code you find in more
advanced topics a little less puzzling.
repaint
manager
validate
pack
18.4
Colors
One colored picture is worth a thousand black and white pictures.
VARIATION ON A CHINESE PROVERB
In this section, we tell you how to specify colors for the figures you draw with the graphics
methods. We also show you how to define your own colors using the class
Color
.