Java By Example PHẦN 5 pdf

59 305 0
Java By Example PHẦN 5 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

classes included in the awt package. Table 16.1 lists the most commonly used drawing methods in the Graphics class. Table 16.1 Drawing Methods of the Graphics Class. Method Description clearRect() Erases a rectangular area of the canvas. copyArea() Copies a rectangular area of the canvas to another area. drawArc() Draws a hollow arc. drawLine() Draws a straight line. drawOval() Draws a hollow oval. drawPolygon() Draws a hollow polygon. drawRect() Draws a hollow rectangle. drawRoundRect() Draws a hollow rectangle with rounded corners. drawString() Displays a text string. fillArc() Draws a filled arc. fillOval() Draws a filled oval. fillPolygon() Draws a filled polygon. fillRect() Draws a filled rectangle. fillRoundRect() Draws a filled rectangle with rounded corners. getColor() Retrieves the current drawing color. getFont() Retrieves the currently used font. getFontMetrics() Retrieves information about the current font. setColor() Sets the drawing color. setFont() Sets the font. To draw a shape in an applet's display area, you only need to call the appropriate method and supply the arguments required by the method. These arguments are based on the coordinates at which you want to draw the shape. For example, the following code example draws a straight line from coordinate 5,10 to 20,30: g.drawLine(5, 10, 20, 30); The g in the preceding code line is the Graphics object passed to the paint() method. As you can see, the drawLine() method takes four arguments, which are X,Y coordinate pairs that specify the starting and ending points of the line. TIP There may be times when you need to retrieve information about the system's currently set graphical attributes. Java's Graphics class supplies methods like getColor(), getFont(), and getFontMetrics() to enable you to obtain this information. Example: Drawing a Rectangle Most of the shape-drawing methods are as easy to use as the drawLine() method is. Suppose that you want to write an applet that draws a filled rounded rectangle inside a hollow rectangle. You'd then add calls to the Graphics class's fillRoundRect() and drawRect() to the applet's paint() method. Listing 16.1 is just such an applet, whereas Listing 16.2 is the HTML document that displays the applet. Figure 16.4 shows the applet running under Appletviewer. Figure 16.4 : This is RectApplet running under Appletviewer. Listing 16.1 RECTAPPLET.JAVA: Drawing Rectangles. import java.awt.*; import java.applet.*; public class RectApplet extends Applet { public void paint(Graphics g) { g.drawRect(35, 15, 125, 200); g.fillRoundRect(50, 30, 95, 170, 15, 15); } } Listing 16.2 RECTAPPLET.htmL: HTML Document for RectApplet. <title>Applet Test Page</title> <h1>Applet Test Page</h1> <applet code="RectApplet.class" width=200 height=250 name="RectApplet"> </applet> In RectApplet's paint() method, you can see the method calls that produce the graphical display. The first line creates the outside rectangle. That method call looks like this: g.drawRect(35, 15, 125, 200); The drawRect() method's four arguments are the X,Y coordinates of the rectangle's upper-left corner and the width and height of the rectangle. The rounded filled rectangle is almost as easy to draw: g.fillRoundRect(50, 30, 95, 170, 15, 15); The first four arguments of the fillRoundRect() method are the same as those for the drawRect() method. The fifth and sixth arguments are the size of the rectangle that represents the rounded corners. Think of this rectangle as being placed on each corner of the main rectangle and a curved line drawn between its corners, as shown in Figure 16.5. Figure 16.5 : The coordinates for the rounded corners are given as the width and height of the rectangle that encloses the rounded corner. Example: Drawing Other Shapes Some shapes you can draw with the Graphics class are more complex than others. For example, the drawArc() method requires six arguments in order to draw a simple curved line. To see how drawing other shapes works, you'll now create the ShapeApplet applet, which enables you to switch from one shape to another in the applet's display. Listing 16.3 is ShapeApplet's source code. Figures 16.6 and 16.7 show what the applet looks like running under the Appletviewer application. Figure 16.6 : This is what ShapeApplet looks like when it first runs. Figure 16.7 : This is ShapeApplet displaying an oval. Listing 16.3 ShapeApplet.java: An Applet That Draws Various Shapes. import java.awt.*; import java.applet.*; public class ShapeApplet extends Applet { int shape; Button button; public void init() { shape = 0; button = new Button("Next Shape"); add(button); } public void paint(Graphics g) { int x[] = {35, 150, 60, 140, 60, 150, 35}; int y[] = {50, 80, 110, 140, 170, 200, 230}; int numPts = 7; switch(shape) { case 0: g.drawLine(35, 50, 160, 230); break; case 1: g.drawRect(35, 50, 125, 180); break; case 2: g.drawRoundRect(35, 50, 125, 180, 15, 15); break; case 3: g.drawOval(35, 50, 125, 180); break; case 4: g.drawArc(35, 50, 125, 180, 90, 180); break; case 5: g.drawPolygon(x, y, numPts); break; case 6: g.fillPolygon(x, y, numPts); break; } } public boolean action(Event event, Object arg) { ++shape; if (shape == 7) shape = 0; repaint(); return true; } } Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive the ShapeApplet class from Java's Applet class. Declare the class's shape data field. Declare the class's button data field. Override the init() method. Initialize the shape counter. Create the applet's Button object. Add the Button object to the applet. Override the paint() method. Initialize the X and Y coordinates for the polygons. Initialize the polygon point count. Display a shape based on the value of the shape counter. Override the action() method. Increment the shape counter. Reset the shape counter if it has reached its maximum value. Force the applet to repaint its canvas with the next shape. Tell Java that the method executed okay. To run ShapeApplet, use the HTML document shown in Listing 16.2, except change all occurrences of RectApplet to ShapeApplet. When you run the applet with Appletviewer, you see the window shown in Figure 16.6. To change the shape displayed in the applet's canvas, click the Next Shape button. Understanding the ShapeApplet Applet You don't need to concern yourself at this point with the button control that ShapeApplet uses to switch shapes, except to know that just like the TextField controls you've been using, clicking the button causes Java to call the applet's action() method. The action() method increments the shape counter, shape, and tells the applet to redraw itself. In the paint() method, the value of shape is used in a switch statement to determine which shape gets drawn. You learned about switch statements back in Chapter 9 "The if and switch Statements." Drawing Ovals The real meat of this program are the calls to the Graphics object's various shape-drawing methods. You already know about the first three: drawLine(), drawRect(), and drawRoundRect(). The call to drawOval(), however, is new and looks like this: g.drawOval(35, 50, 125, 180); As you can see, this method, which draws ovals and circles, takes four arguments. These arguments are the X,Y coordinates, width, and height of a rectangle that can enclose the oval. Figure 16.8 shows how the resultant oval relates to its enclosing rectangle. Figure 16.8 : An oval's coordinates are actually the coordinates of an enclosing rectangle. Drawing Arcs Next in paint() is the drawArc() method, which is the most complicated (at least, from an understanding point of view) of the shape-drawing methods. The call to drawArc() looks like this: g.drawArc(35, 50, 125, 180, 90, 180); The first four arguments are the same as the arguments for drawOval(): the X,Y coordinates, width, and height of the enclosing rectangle. The last two arguments are the angle at which to start drawing the arc and the number of degrees around the arc to draw. To understand all this angle nonsense, take a look at figure 16.9, which shows how Java relates the arc's starting angle to the degrees of an oval. In the preceding example call to drawArc(), the fifth argument is 90, which means Java starts drawing the arc, within the arc's enclosing rectangle, at the 90-degree point. The sixth argument of 180 tells Java to draw around the arc 180 degrees (or halfway around the full 360 degrees). It doesn't mean that the ending point should be at the 180-degree point. Figure 16.10 shows the resultant arc. Figure 16.9 : The degrees of an oval start on the right side and travel counter-clockwise around the arc. Figure 16.10 : The arc shown here starts at the 90-degree point and sweeps 180 degrees around the arc. Example: Drawing Arcs in an Applet Because understanding the angles involved in drawing arcs can be a little confusing, in this example you'll create an applet called ArcApplet that enables you to enter different values for drawArc()'s fifth and sixth arguments and immediately see the results. Listing 16.4 is the source code for the applet. Use Listing 16.2 to create ArcApplet's HTML document, by changing each occurrence of RectApplet to ArcApplet. Listing 16.4 ARCAPPLET.JAVA: An Arc-Drawing Applet. import java.awt.*; import java.applet.*; public class ArcApplet extends Applet { TextField textField1, textField2; public void init() { textField1 = new TextField(10); textField2 = new TextField(10); add(textField1); add(textField2); textField1.setText("0"); textField2.setText("360"); } public void paint(Graphics g) { String s = textField1.getText(); int start = Integer.parseInt(s); s = textField2.getText(); int sweep = Integer.parseInt(s); g.drawArc(35, 50, 125, 180, start, sweep); } public boolean action(Event event, Object arg) { repaint(); return true; } } Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive the ArcApplet class from Java's Applet class. Declare the class's TextField objects. Override the init() method. Create the two TextField objects. Add the TextField objects to the applet. Set the text for the TextField objects. Override the paint() method. Get the starting angle and convert it to an integer. Get the sweep angle and convert it to an integer. Display the selected arc. [...]... "Name: " + name; g.drawString(s, 50 , 50 ); s = "Family: " + family; g.drawString(s, 50 , 65) ; s = "Style: " + style; g.drawString(s, 50 , 80); s = "Size: " + size; g.drawString(s, 50 , 95) ; g.drawString(info, 20, 1 25) ; } } Tell Java that the applet uses the classes in the awt package Tell Java that the applet uses the classes in the applet package Derive the FontApplet class from Java' s Applet class Override... like this: int x[] = { 35, 150 , 60, 140, 60, 150 , 35} ; int y[] = {50 , 80, 110, 140, 170, 200, 230}; int numPts = 7; The first array, called x[] in the preceding, is the X coordinates for each X,Y pair, and the second array, called y[], is the Y coordinates for each X,Y pair By looking at the values defined in the arrays, you can see that the first line gets drawn from 35, 50 to 150 ,80 Because all the... fontMetrics.stringWidth(s); String width = String.valueOf(n); g.drawString("FONT INFO:", 55 , 60); g.drawString("Leading: " + leading, 70, 80); g.drawString("Ascent: " + ascent, 70, 95) ; g.drawString("Descent: " + descent, 70, 110); g.drawString("Height: " + height, 70, 1 25) ; g.drawString("STRING INFO:", 55 , 155 ); g.drawString("Width: " + width, 70, 1 75) ; } public boolean action(Event event, Object arg) { repaint(); return... of text you need to print Listing 17 .5, which is the source code for the FontApplet2 applet, shows how this is done Listing 17.6 is the applet's HTML document, and Figure 17 .5 shows what the applet looks like Figure 17 .5 : This is Appletviewer running the FontApplet2 applet Listing 17 .5 FontApplet2 .java: Displaying Different Sized Fonts import java. awt.*; import java. applet.*; public class FontApplet2... to the applet by using the add() method, like this: add(label); Example: Creating a Label Suppose that you want a centered label that displays the text Java does labels! To do this, you use a line of Java code something like this: Label label = new Label( "Java does labels!", Label.CENTER); Of course, you can also store the text to display in a String object, like this: String str = "Java does Labels!";... describes some aspect of the font represented by the Font object Getting Font Metrics In many cases, the information you can retrieve from a Font object is enough to keep you out of trouble For example, by using the size returned by the getSize() method, you can properly space the lines of text Sometimes, though, you want to know more about the font you're using For example, you might want to know the width... Attributes r Example: Displaying Font Information r Getting Font Metrics r Example: Displaying Font Metrics Creating Fonts r Example: Creating a Font with Multiple Styles r Using the Font r Example: Displaying Different Sized Fonts Summary Review Questions Review Exercises Now that you know how to draw all kinds of shapes in your applets, it's time to see how to use text and text fonts, as well By combining... defined in the arrays, you can see that the first line gets drawn from 35, 50 to 150 ,80 Because all the lines in a polygon are connected, Java can continue drawing lines by using the previous ending point (in this case, 150 ,80) and the next coordinate pair, which is 60,110 Java will continue to work through the arrays until it uses all the given coordinates The actual method call that draws the polygon looks... current graphics settings In the next chapter, you add to your graphics knowledge by learning how to create, manipulate, and display graphical text Review Questions 1 2 3 4 5 What do you call the area of an applet in which you can draw? How is Java' s graphical coordinate system organized? What is the difference in the shapes drawn by the drawRect() and fillRect() methods? What are the four arguments for the... the name to fill For example, because drawArc() draws a hollow arc, the method fillArc() draws a filled arc Drawing Polygons Polygons are simply many-sided shapes For example, a triangle is a polygon (it is, in fact, the simplest polygon) Squares, rectangles, and hexagons are all polygons, as well Because a polygon comprises many different lines, before you can draw a polygon in Java, you need to create . 1 25, 180); break; case 2: g.drawRoundRect( 35, 50 , 1 25, 180, 15, 15) ; break; case 3: g.drawOval( 35, 50 , 1 25, 180); break; case 4: g.drawArc( 35, 50 , 1 25, 180, 90, 180); break; case 5: . = { 35, 150 , 60, 140, 60, 150 , 35} ; int y[] = {50 , 80, 110, 140, 170, 200, 230}; int numPts = 7; switch(shape) { case 0: g.drawLine( 35, 50 , 160, 230); break; case 1: g.drawRect( 35, 50 ,. g.drawString(s, 50 , 50 ); s = "Family: " + family; g.drawString(s, 50 , 65) ; s = "Style: " + style; g.drawString(s, 50 , 80); s = "Size: " + size; g.drawString(s, 50 , 95) ;

Ngày đăng: 12/08/2014, 19:21

Từ khóa liên quan

Mục lục

  • Java By Example

    • Chapter 17 -- Graphical Text

    • Chapter 18 -- Label and Button Controls

    • Chapter 19 -- Checkbox and TextField Controls

    • Chapter 20 -- Choice Menu, Text Area, and Scrolling List Controls

Tài liệu cùng người dùng

Tài liệu liên quan