Painting with a Graphics Object
Problem
You want to draw something on the screen.
Solution
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); } }
Discussion
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
.
When to draw?
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 ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.