9.1. Computer Graphics in Java

Writing a program to generate designs of this sort requires more than an understanding of its recursive structure. To see these programs work and thereby experience some of the excitement of computer graphics, you need to learn how to display graphical patterns on your computer. Java's libraries offer extensive graphical capabilities through its standard application programmer interfaces (APIs), but these facilities are often difficult for novices to use and are not well suited for drawing recursive patterns. To get around these problems, the programs in this chapter make use of the GPen class, which is defined in the acm.graphics package developed by the Association for Computing Machinery (ACM) for pedagogical use. The methods in the GPen class that you need to know are

  • setLocation(x, y), which moves the pen to the specified location without drawing a line

  • drawLine(dx, dy), which draws a line starting at the current pen position and extending dx units horizontally and dy units vertically

  • drawPolarLine(r, theta), which draws a line from the current pen position whose length is r units and which moves in the direction theta, measured in degrees counterclockwise from the +x axis.

As in the traditional Java libraries, the coordinate system is measured in pixels, with x values increasing to the right and y values increasing downward.

To get a better sense of the operation of these methods, imagine that you are using a pen on a large piece of graph paper ...

Get Thinking Recursively with Java 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.