Java Reference
In-Depth Information
segments—
setColor
/
getColor
,
setFont
/
getFont
, and many other methods. Too many to
list here, in fact; see the online documentation for
java.awt.Graphics
.
When to draw?
In the past, a common beginner's mistake was call
getGraphics()
and call the
Graphics
object's drawing methods from within a main program or the constructor of a
Component
subclass. Fortunately, we now have any number of books to tell us that the correct way to
draw anything is with your component's paint method. Why? Because you can't draw in a
window until it's actually been created and (on most window systems) mapped to the screen,
which takes much more time than your main program or constructor has. The drawing code
needs to wait patiently until the window system notifies the Java runtime that it's time to
paint the window.
Where do you put your drawing code? This is one situation where you need to think about
AWT versus Swing. AWT, the basic windowing system, uses a method called
paint()
. This
method is still available in Swing, but due to interaction with borders and the like, it is re-
commended that you override
paintComponent()
instead. Both are called with a single ar-
gument of type
Graphics
. Your
paintComponent()
should start by calling
su-
per.paintComponent()
with the same argument to ensure that components are painted in
proper back-to-front order, whereas
paint()
should not call its parent. Some examples in
this chapter use
paint()
and others use
paintComponent()
; the latter also usually extend
JPanel
. This allows better interaction with Swing, and also allows you to place these as the
main component in a
JFrame
by calling
setContentPane()
, which eliminates an extra layer
Showing Graphical Components Without Writing Main
Problem
You don't want to have to write a little main program with a frame each time you write a
subclass of
Component
.