In your paint( )
method, use the provided
Graphics
object’s drawing methods:
// graphics/PaintDemo.java import java.awt.*; public class PaintDemo extends Component { int rectX = 20, rectY = 30; int rectWidth = 50, rectHeight = 50; public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(rectX, rectY, rectWidth, rectHeight); } public Dimension getPreferredSize( ) { return new Dimension(100, 100); } }
The Graphics
class has a large set of drawing
primitives. For each of
Rect(angle), Arc, Ellipse, and Polygon,
there is a draw method (draws just the outline) and a fill method
(fills inside the outline). You don’t need both, unless you
want the outline and the interior (fill) of a shape to be different
colors. The method drawString( )
and related methods let you print
text on the screen (see Section 12.4). There are also
drawLine( )
, which draws straight line segments,
setColor
/getColor
,
setFont
/getFont
, and many other
methods. Too many to list here, in fact; see Sun’s online
documentation for java.awt.Graphics
.
A common beginner’s mistake used to be to 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, and that 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
(and the only one in JDK 1.1) uses a method called paint( )
. This
method is still available in Swing, but due to interaction with
borders and the like, it is recommended that you override
paintComponent( )
instead.
Both are called with a single argument of type
Graphics
. Your paintComponent( )
should start by calling super.paintComponent( )
with the same argument to ensure that components are
painted in proper back-to-front order, while 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 of container.
(JFrame
’s ContentPane
is
discussed in Section 13.2.)
3.144.17.128