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

Drawing Text with 2D

Problem

You want fancier drawing abilities.

Solution

Use a Graphics2D object.

Discussion

The subject of the 2D graphics added in Java 2 could be the subject of an entire book, and in fact, it is. Java 2D Graphics by Jonathan Knudsen (O’Reilly) covers every imaginable aspect of this comprehensive new graphics package. Here I’ll just show one example, that of drawing text with a textured background.

The Graphics2D class is a direct subclass of the original Java Graphics object. In fact, in Java 2, your paint( ) method is always called with an instance of Graphics2D. So, it suffices to begin your paint method by casting appropriately:

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

You can then use any Graphics2D methods or any regular Graphics methods, getting to them with the object reference g2. One of the additional methods in Graphics2D is setPaint( ), which can take the place of setColor( ) to draw with a solid color. However, it can also be called with several other types, and in this case we pass in an object called a TexturePaint, which refers to a pattern. Our pattern is a simple set of diagonal lines, but any pattern or even a bitmap from a file (see Section 12.7) can be used. Figure 12-5 shows the resulting screen (it looks even better in color).

TexturedText: a tiny sample of the 2D API

Figure 12-5. TexturedText: a tiny sample of the 2D API

The program that produced this is shown ...

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