5. Objects: Using, Creating, and Defining

5.2. Drawing Shapes with a Graphics Object (Optional)

All of the instance methods of the String class that we examined return values. The length() method return an int value, and the concat() method returned a String. It is also very common for classes to define instance methods that perform actions but do not return a value. The Graphics object, g, that appears in Chapter 1’s HelloWorldSwing is one example. The program is reproduced in Figure 2.5

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 2.5: HelloWorldCanvas program source code.

 

SECTION 2.3 Drawing Shapes with a Graphics Object (Optional) 67

At this point we will not worry about the language features that en- able the paint() method to draw on the Java Swing window. We will focus instead on the information needed to make good use of the g.drawString() method. The first thing you should know is that, when the paint() method is executed, its parameter, g, refers to an instance of the Graphics class. Unlike our other examples involving variables that refer to objects, in this case there is no need to use a constructor to create an object of type Graphics. We can assume g already refers to such an object.

We already know that the statement

,,

 

J

displays the String “Hello, World!” in the program window. More gen- erally, if str is a literal String value or a reference to a String object and x and y are literal int values or int variables then

,,

 

J

displays the String str from left to right in the program window be- ginning at a point which is x pixels from the left edge of the window and y pixels down from the top edge of the window. In a graphics window, the point with coordinates (0,0) is at the top-left corner. The horizontal axis grows positively from left to right. The vertical axis grows positively from top to bottom (Fig. 2.6).

(A pixel is a dot on the console window that can be set to a certain

color.) Notice that increasing the value of y will cause str to be displayed

 

lower. This is the opposite of the usual x and y coordinate system used in mathematics where increasing the y value designates a higher point.

With this information about g.drawString(), we can calculate where to display any message in the program window. For example, if we wish to display the message “Welcome to Java” 25 pixels below where “Hello, World!” is displayed we could use the statements


Figure 2.6: Coordinate system of a Java window.

 

,,

 

J

in the body of HelloWorldCanvas’s paint() method. The result of these statements would appear as shown in Figure 2.7.

Graphics Drawing Methods

The Graphics class discussed in the previous section also has methods that can be used to draw geometric shapes in different colors. These meth- ods can be used to create graphical user interfaces that are more interest- ing or to give a visual representation of data, such as a pie chart or a bar graph.

There are two Graphics methods for drawing rectangles, fillRect() and drawRect() (Fig. 2.8). The first draws a rectangle and fills it with the current drawing color and the second just draws the outline of the rectan- gle. Using the Graphics object, g, each of these is called in the same way

 

Figure 2. drawn at “Welcom the JFram

 

 

 

 

 

 

 

 

 

 

as the drawString() method from the previous example. Each of these methods takes four int arguments, which specify the rectangle’s location and size. Thus, a call to fillRect() would take the form

,,

 

 

 

 

 

 

 

 

Figure 2.8: Some of the drawing methods in the Graphics class.


J

where x and y arguments specify the location of the upper left corner of the rectangle as being x pixels from the left edge of the window and y pixels down from the top edge of the window. The width and height arguments specify the width and height of the rectangle in pixels. The drawRect() method also takes the same four arguments.

A Graphics object stores a single color for use in drawing shapes or displaying strings with drawString(). If we wish to draw an interesting scene in the JFrame, we need to understand how to use colors.

For a given Graphics object, such as g, the setColor() method will set its color for all subsequent drawing commands. The setColor() method takes, as an argument, an object of type Color. All we need to know about the Color class is that it is contained in the java.awt package and that it contains 13 constant Color objects corresponding to 13 common colors. Table 2.1 lists the 13 Color constants. Each name corresponds to the color it will represent in the program.

 

 

Color.black

Color.green

Color.red

Color.blue

Color.lightGreen

Color.white

Color.cyan

Color.magenta

Color.yellow

Color.darkGray

Color.orange

 

Color.gray

Color.pink

 

Table 2.1: Predefined color constants in the Color class.

 

 

To demonstrate how the new Graphics methods can be used for cre- ating more interesting graphical programs, let’s develop a plan for dis- playing the two messages, “Hello, World!” and “Welcome to Java.”, on an JFrame, but this time we will draw the first inside a colored rectan- gle and the second inside a colored oval. For the rectangle, let’s use the

 

drawRect() method to create its border. We can choose some arbitrary colors, say, cyan for filling the rectangle, blue for its border, and black for the string itself. In order to have the message visible we should fill a rectangle with the color cyan first, then draw the border of the rectangle in blue and, finally, display the message in black.

Drawing and filling a Graphics oval is very similar to drawing and filling a rectangle. Notice in Figure 2.8 that the fillOval() and drawOval() methods take the same four arguments as the correspond- ing rectangle methods. An oval is inscribed within an enclosing rectangle. The x and y arguments give the coordinates of the enclosing rectangle’s top left point. And the width and height arguments give the enclosing rectangles dimensions.

All that remains is to choose the location and dimensions of the rect- angles. We could specify one rectangle as having its upper left corner 25 pixels to the right of the left edge of the JFrame and 25 pixels down from the top edge. A medium sized rectangle could have a width of 140 pixels and a height of 40 pixels. The statement

,,

 

J

will fill this rectangle with whatever color happens to be g’s current color. A location 25 pixels to the right of the left edge of the rectangle and 25 pixels down from the top edge of the rectangle would have coordinates x = 50 and y = 50. Thus, the statement

,,

 

J

will display “Hello, World!” inside the rectangle. We can use similar planning to locate the oval and its enclosed message.

Thus, we now have sufficient information to finish the paint() method for accomplishing our plan. The completed program is displayed in Figure 2.9. Note how we repeatedly use the g.setColor() method to change g’s current color before drawing each element of our picture.

Figure 2.10 shows what this program looks like. To experiment with

this Java Swing application, download its sourcecode from the book’s Web site and compile and run it on your computer. Additional drawing capa- bilities will be explored throughout the text in sections that can either be covered or skipped.