Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata