O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required