⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch16.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
The first four arguments are the same as the arguments for <TT>drawOval()</TT>:the X,Y coordinates, width, and height of the enclosing rectangle.The last two arguments are the angle at which to start drawingthe arc and the number of degrees around the arc to draw.<P>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 degreesof an oval. In the preceding example call to <TT>drawArc()</TT>,the fifth argument is 90, which means Java starts drawing thearc, within the arc's enclosing rectangle, at the 90-degree point.The sixth argument of 180 tells Java to draw around the arc 180degrees (or halfway around the full 360 degrees). It doesn't meanthat the ending point should be at the 180-degree point. Figure16.10 shows the resultant arc.<P><A HREF="f16-9.gif"><B> Figure 16.9 : </B><I>The degrees of an oval start on the right side and travel counter-clockwise around the arc.</I></A><P><P><A HREF="f16-10.gif"><B> Figure 16.10 : </B><I>The arc shown here starts at the 90-degree point and sweeps 180 degrees around the arc.</I></A><P><H3><A NAME="ExampleDrawingArcsinanApplet">Example: Drawing Arcs in an Applet</A></H3><P>Because understanding the angles involved in drawing arcs canbe a little confusing, in this example you'll create an appletcalled ArcApplet that enables you to enter different values for<TT>drawArc()</TT>'s fifth and sixth arguments and immediatelysee the results. Listing 16.4 is the source code for the applet.Use Listing 16.2 to create ArcApplet's HTML document, by changingeach occurrence of RectApplet to ArcApplet.<HR><BLOCKQUOTE><B>Listing 16.4&nbsp;&nbsp;ARCAPPLET.JAVA: An Arc-Drawing Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>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(&quot;0&quot;);        textField2.setText(&quot;360&quot;);    }    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;    }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the applet uses the classes in the <TT>awt</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>applet</TT>package.<BR>Derive the <TT>ArcApplet</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare the class's <TT>TextField</TT> objects.<BR>    Override the <TT>init()</TT> method.<BR>        Create the two <TT>TextField</TT> objects.<BR>        Add the <TT>TextField</TT> objects to the applet.<BR>        Set the text for the <TT>TextField</TT> objects.<BR>    Override the <TT>paint() </TT>method.<BR>        Get the starting angle and convert it to an integer.<BR>        Get the sweep angle and convert it to an integer.<BR>        Display the selected arc.<BR>    Override the <TT>action()</TT> method.<BR>        Force the applet to repaint its canvas with the next shape.<BR>        Tell Java that the method executed okay.</BLOCKQUOTE><P>When you run ArcApplet using Appletviewer, you see the windowshown in Figure 16.11. (Looks kind of like a guy with shifty eyesand a big nose, doesn't it?) Because the starting angle (in thefirst text box) is 0 and the drawing degrees (the second box)is 360, the arc is actually a full oval. By changing the valuesin the two boxes and pressing Enter, you can cause the appletto display different arcs. For example, Figure 16.12 shows anarc that has a starting angle of 120 degrees and drawing degreesof 245.<P><P><A HREF="f16-11.gif"><B> Figure 16.11 : </B><I>This is ArcApplet at startup.</I></A><P><A HREF="f16-12.gif"><B> Figure 16.12 : </B><I>You can use ArcApplet to experiment with different arc angle settings.</I></A><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Most of the shape-drawing methods come in two versions, one that draws a hollow shape and one that draws a filled shape. The method that draws the filled shape has the same name as the one that draws the hollow shape, except you change the word <TT>draw</TT> in the name to <TT>fill</TT>. For example, because <TT>drawArc()</TT> draws a hollow arc, the method <TT>fillArc()</TT> draws a filled arc.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="DrawingPolygons">Drawing Polygons</A></H3><P>Polygons are simply many-sided shapes. For example, a triangleis a polygon (it is, in fact, the simplest polygon). Squares,rectangles, and hexagons are all polygons, as well. Because apolygon comprises many different lines, before you can draw apolygon in Java, you need to create arrays that contain the X,Ycoordinates for each line in the polygon. In Listing 16.3, ShapeAppletdefines those arrays like this:<BLOCKQUOTE><PRE>int x[] = {35, 150, 60, 140, 60, 150, 35};int y[] = {50, 80, 110, 140, 170, 200, 230};int numPts = 7;</PRE></BLOCKQUOTE><P>The first array, called <TT>x[]</TT> in the preceding, is theX coordinates for each X,Y pair, and the second array, called<TT>y[]</TT>, is the Y coordinates for each X,Y pair. By lookingat the values defined in the arrays, you can see that the firstline gets drawn from 35,50 to 150,80. Because all the lines ina polygon are connected, Java can continue drawing lines by usingthe previous ending point (in this case, 150,80) and the nextcoordinate pair, which is 60,110. Java will continue to work throughthe arrays until it uses all the given coordinates. The actualmethod call that draws the polygon looks like this:<BLOCKQUOTE><PRE>g.drawPolygon(x, y, numPts);</PRE></BLOCKQUOTE><P>The <TT>drawPolygon()</TT> method's three arguments are the arrayholding the X coordinates, the array holding the Y coordinates,and the number of points defined in the arrays. You can use aliteral value for the third argument, but it's often handy todefine a variable as shown in the example (<TT>numPts</TT>). Then,if you change the arrays, you can change the variable at the sametime and not have to worry about correcting any method calls thatuse the arrays along with point count.<P>Figure 16.13 shows the polygon drawn by the values given in the<TT>x[]</TT> and <TT>y[]</TT> arrays in the preceding. Looks morelike a squiggly line than a polygon. That's because when you drawa hollow polygon, Java doesn't connect the starting and endingpoint. If you draw a filled polygon, though, you'll see that theconnecting side is really there, as shown in Figure 16.14.<P><A HREF="f16-13.gif"><B> Figure 16.13 : </B><I>A hollow polygon is always missing one side.</I></A><P><P><A HREF="f16-14.gif"><B> Figure 16.14 : </B><I>A filled polygon actually looks like a polygon instead of a squiggly line.</I></A><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>If you need more control over your polygons, Java includes a <TT>Polygon</TT> class from which you can create polygon objects from the coordinate arrays. The <TT>Polygon</TT> class includes handy methods that enable you to add points to a polygon, determine whether a point is inside the polygon, and retrieve the polygon's bounding rectangle. You create a <TT>Polygon</TT> object with a line like <TT>Polygon polygon = new Polygon(x, y, numPts)</TT>. The arguments for the class's constructor are the same as those for the <TT>drawPolygon()</TT> method. The <TT>Polygon</TT> class's public methods are <TT>addPoint(x, y)</TT>, <TT>getBoundingBox()</TT> (which returns a <TT>Rectangle</TT> object), and <TT>inside()</TT> (which returns a <TT>boolean</TT> value).</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Java's <TT>Graphics</TT> class enables you to draw many typesof shapes, including lines, rectangles, ovals, and arcs. You canuse these shape-drawing methods to enhance the appearance of yourapplets, drawing frames around objects, and even putting togethersimple illustrations. In addition, you can set the drawing colorused by the <TT>Graphics</TT> class, as well as query the systemfor its current graphics settings. In the next chapter, you addto your graphics knowledge by learning how to create, manipulate,and display graphical text.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What do you call the area of an applet in which you can draw?<LI>How is Java's graphical coordinate system organized?<LI>What is the difference in the shapes drawn by the <TT>drawRect()</TT>and <TT>fillRect()</TT> methods?<LI>What are the four arguments for the <TT>drawRect()</TT> method?<LI>How do the arguments for the <TT>drawRoundRect()</TT> methoddiffer from the arguments for <TT>drawRect()</TT>?<LI>Why does the <TT>drawPolygon()</TT> method require that youset up arrays of coordinates?<LI>What are the six arguments required by the <TT>drawArc()</TT>method?<LI>Why would you want to use the <TT>polygon</TT> class?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write the code needed to draw a 100&#180;200 rectangle atthe coordinates 50,75.<LI>Write an applet that displays a square inside a circle.<LI>Write an applet that enables the user to choose the width,height, and location of a rectangle. The applet should displaythe rectangle at the given coordinates.<LI>Modify the ArcApplet applet so that the user can select notonly the arc's drawing points, but also the size of the arc'sbounding rectangle.<LI>Write an applet called FaceApplet that displays a face madefrom ovals and arcs. The final applet should look like Figure16.15. (You can find the solution to this problem in the CHAP16folder of this book's CD-ROM.) <BR><A HREF="f16-15.gif"><B> Figure 16.15 : </B><I>This is what FaceApplet should look like when running under Appletviewer.</I></A><P></OL><HR><HR WIDTH="100%"></P></CENTER><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>,  All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -