1.7. Hello, 2D!

This chapter ends with a bang—an example that demonstrates the power of the 2D API. You probably won't understand much of the code at this point, but rest assured that it all will become clear as you work through the rest of the book.

In general terms, this is what the example does:

  • The example draws a background of colored circles.

  • Then the example draws an image. The image is broken into small pieces, and each piece is drawn partially transparent, allowing the circles to show through. The image is Raphael's self-portrait, taken from the Virtual Uffizi at http://www.arca.net/uffizi/.

  • Finally, the example draws some text on a color-gradient-filled background. Then the text is drawn a second time, rotated 90°.

The results are shown in Figure 15.1. This is a less than 200 lines of code (with lots of comments). It's a small subset of what can be accomplished with the 2D API.

Note that this example depends on the ApplicationFrame class presented earlier in this chapter. If you haven't entered and compiled ApplicationFrame, do it now.[3]

[3] Like all the other examples in this book, ShowOff is available online. See the the preface for details.

import java.awt.*; import java.awt.event.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.Random; import com.sun.image.codec.jpeg.*; public class ShowOff extends Component { public static void main(String[] args) { try { // The image is loaded either from this ...

Get Java 2D Graphics 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.