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

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.