Section 2.3. Drawing Shapes with a Graphics Object (Optional)


[Page 68 (continued)]

2.3. Drawing Shapes with a Graphics Object (Optional)

All of the instance methods of the String class that we have examined return values. The length() method returns an int value, and the concat() method returns a String. Classes also very commonly define instance methods that perform actions but do not return a value. The Graphics object, g, that appears in Chapter 1's HelloWorldApplet is one example. The program is reproduced in Figure 2.5.

Figure 2.5. HelloWorldApplet program.
(This item is displayed on page 69 in the print version)

  /*    * HelloWorldApplet program    */ import java.applet.Applet;                   // Import the Applet class import java.awt.Graphics;                    //  and the Graphics class public class HelloWorldApplet extends Applet // Class header {                                            // Start of body   public void paint(Graphics g)              // The paint method   {     g.drawString("Hello World",10,10);   }                                          // End of paint }                                            // End of HelloWorld 

At this point we will not worry about the language features that enable the paint() method to draw on the applet window when the applet is executed by a Web browser. 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 that g already refers to such an object.


[Page 69]

We already know that the statement

g.drawString("Hello World",10,10); 


displays the String "Hello World" in the applet window. More generally, 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

g.drawString(str,x,y) 


displays the String str from left to right in the applet window, beginning 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 an applet 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.) Note 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.

Figure 2.6. Coordinate system of a Java window.



[Page 70]

With this information about g.drawString(), we can calculate where to display any message in the applet 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

g.drawString("Hello World",10,10); g.drawString("Welcome to Java",10,35); 


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

Figure 2.7. "Hello World" is drawn at coordinate (10, 10) and "Welcome to Java" at (10, 35) in the applet window.


2.3.1. Graphics Drawing Methods

The Graphics class discussed in the preceding section also has methods that can be used to draw geometric shapes in different colors. These methods can be used to create graphical user interfaces that are more interesting 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 rectangle. Using the Graphics object, g, each of these is called in the same way 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

g.fillRect(x,y,width,height); 



[Page 71]

where x and y arguments specify the location of the upper-left corner of the rectangle as 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.

Figure 2.8. Some of the drawing methods in the Graphics class.
(This item is displayed on page 70 in the print version)


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 applet window, 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.

Table 2.1. Predefined color constants in the Color class.

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

  


To demonstrate how the new Graphics methods can be used for creating more interesting applets, let's develop a plan for displaying the messages "Hello World" and "Welcome to Java" on an applet, but this time we will draw the first message inside a colored rectangle and the second inside a colored oval. For the rectangle, let's use the drawRect() method to create its border. We can choose colors arbitrarily, 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. Note in Figure 2.8 that the fillOval() and drawOval() methods take the same four arguments as the corresponding 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 rectangle's dimensions.

All that remains is to choose the location and dimensions of the rectangles. We could specify one rectangle as having its upper-left corner 25 pixels to the right of the left edge of the applet window 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

g.fillRect(25, 25, 140, 40); 


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

g.drawString("Hello World", 50, 50); 



[Page 72]

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.9. The HelloWorldGraphic class is an applet that shows how to use color and drawing methods.

import java.awt.*; import java.applet.*; public class HelloWorldGraphic extends Applet { public void paint(Graphics g)   { g.setColor(Color.cyan);                     // Set color     g.fillRect(25, 25, 140, 40);                // Fill rectangle     g.setColor(Color.blue);                     // Set color     g.drawRect(25, 25, 140, 40);                // Outline rectangle     g.setColor(Color.black);                    // Set color     g.drawString("Hello World", 50, 50);        // Display string     g.setColor(Color.yellow);     g.fillOval(25, 75, 140, 40);                // Fill oval     g.setColor(Color.red);     g.drawOval(25, 75, 140, 40);                // Outline oval     g.setColor(Color.black);     g.drawString("Welcome to Java", 50, 100);   } // paint() } // HelloWorldGraphic class 

Figure 2.10 shows what this applet looks like when run in a browser. To experiment with this applet, download its source code and its corresponding HTML file from the book's Web site, and compile and run it on your computer. If you've forgotten how to run an applet, review Section 1.5.5. Additional drawing capabilities will be explored throughout the text in sections that can either be covered or skipped.


[Page 73]

Figure 2.10. This is how the HelloWorldGraphic applet will look when run in a browser.
(This item is displayed on page 72 in the print version)





Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net