424 Understanding the Abstract Windowing Toolkit (AWT)
424 了解抽象窗口工具AWT(Abstract Windowing Toolkit)
In the early daysof the computer age, developing a graphical application often required detailedknowledge of the underlying graphics hardware. Just imagine having to programat the register level or having to map between memory addresses and screencoordinates! Even today, creating a graphics program that runs on differentplatforms can still be a challenge. For example, you will have to learn theWindows API (Application Programming Interface) to program on the MicrosoftWindows platform and, perhaps, MOTIF on an X-Window platform.
在计算机早期年代里,开发一个带有图形的应用程序通常要求人们具有有关图形硬件的详细知识。一般设计必须采用寄存器级的编程或必须在内存地址与屏幕坐标之间进行映射。即使是在今天,编制一个在不同平台上都能运行的程序仍然是一项具有挑战性的工作。例如,你必须学习Windows的应用程序接口API (Application Programming Interface) 才能在Microsoft的Windows平台上编制程序,或者,你必须学习MOTIF才能在X-Window平台上进行编程。
By contrast, one ofthe strengths of Java is that it is platform independent. Javas AbstractWindowing Toolkit (AWT) package provides a set of platform-independent classesthat handle graphics operations. For example, you can create a command buttonusing the Button constructor, regardless of the platform on which the Java codeis going to run. The actual button may be implemented through native codes andlook a little different on each platform, but you do not have to programdifferently.The AWT package includes classes for drawing lines, and creatingcommand buttons, pull-down menus, dialog boxes, and so on. To use JavasAbstract Windowing Toolkit package, you must import it using the followingstatement:
与此相反,Java语言强有力的特点之一就是在于它与平台无关。Java的AWT(抽象窗口工具)提供了一组与平台无关的能处理图形操作的类。例如,你可利用Button constructor (按钮构造器) 来构造一个命令按钮,而不管这Java程序是要到什么平台去运行。实际的按钮需要通过机器本身的代码来实现,而且对不同的平台会有一点差别,但你并不需要编写不同的程序。AWT所包含的类可用来画直线,创建命令按钮,创建下拉式菜单和对话框,等等。为了使用Java的抽象窗口工具包,你必须利用以下这个语句来引用它:
import java.awt.*;
Although you canspecify the package each time it is used, it is much more convenient to use theimport statement. The following tips in this section will show you how to usethe classes in Javas AWT package.
你可以在每一次用到这一个包的时候进行说明, 但更方便的是使用import (输入、引入、引用)语句.本节以下的几个TIP将向你说明怎样使用Java的AWT包中的一些类.
425Looking at the AWT Class Hierarchy
425考察一下AWT类的体系结构
As you learned inthe previous tip, Javas Abstract Windowing Toolkit provides a collection ofmethods your programs can use to perform graphics operations. Figure 425 showsthe AWT class hierarchy. This hierarchy should give you a good idea of the AWTsrich set of graphics features available.Production: Insert AWT class hierarchyfigure。
你在上一个TIP中已知道,Java的抽象窗口工具AWT提供了在程序中用来实现图形操作的一组方法. 图425说明了AWT类的层次结构,这一结构体系应能给你一个有关AWT可用的丰富图形功能的良好印象吧!
Figure 425 AWT class hierarchy.
图425 AWT类的层次结构
426Understanding Graphics Objects
426了解Graphics对象(图形学对象)
Before your appletscan draw lines or text on the screen, you must first obtain the Graphicsobject. In fact, much of Javas graphics operations are Graphics class methods.Your program can obtain the Graphics object (the graphics context) from theparameter passed through the update or paint method. The Graphics objectcontains the current color, font, origin location, and so on. Java will use theGraphics object in each of its drawing operations. The following statementsillustrate the use of the graphics context within the paint method:
在你的applets(小应用程序)[译注:这一译名不是最好,因为要和small application混淆,但实际applet是一个专有名字,是一种能在网上被直接看到的程序,它实际也可以不小,可以比某些应用程序为大;也有人使用小程序作为applet译名,但也一样,要和小的程序混淆。我认为,必须考虑一个新名字,建议译为应用子,或者干脆不译,就叫applet。因众多文献已经习惯使用小应用程序或小程序了,怕改后人们反而不懂,故本文仍采用小应用程序或小程序作为applet的译名] 能在屏幕上画线条、写文字之前,你必须首先得到Graphics对象(绘图环境)。实际上, 大量的Java图形操作都是Graphics类方法。你的程序可以从由opdate方法或paint方法传递过来的参数中得到Graphics对象。Graphics对象包括当前的颜色,当前的字体,原点的位置,等等。Java将在它的每一个作图操作中使用到Graphics对象。以下这些语句说明了在paint方法中使用图形对象的方法。
public void paint(Graphics g)
{
// display entire string
g.drawString( ”1001 Java Programmers Tips“, 5, 10);
}
427Understanding Javas Coordinate System
427弄清Java的坐标系统
Before you examineJavas Abstract Windowing Toolkit, you should first understand Javas coordinatesystem. Many of the AWT class methods use an x-y coordinate system to positionthe item to be drawn. For example, to draw a line using the drawLine method,your programs use the parameters x1, y1, x2, y2 to specify the lines startingand ending coordinates. The default location of the origin (0, 0) on the screenis at the top-left corner with positive X extending to the right and positive Yextending to the bottom, as shown in Figure 427.
在你考查Java的抽象窗口工具之前,你首先应了解Java的坐标系统。许多的AWT类方法使用x-y坐标系统来确定图形元素项目要画的地方。例如,为了使用drawLine方法来画一根直线,你的程序要使用x1,y1,x2,y2四个参数来说明该直线的起点和终点的坐标。原点(0,0)在屏幕上的缺省位置是在左上角,并规定X向右伸展为正,Y向屏幕底部伸展为正,如图427所示。
Figure 427 Default Java coordinatesystem.
图427 缺省的Java坐标系统
428Drawing a String
428画字符串
As you havelearned, you can display a String object on the screen using the drawStringmethod. The drawString method, as shown, lets you display a String at theposition specified by the x and y parameters:
正如你已知道的那样,你可以使用drawString方法在屏幕上显示一个字符串对象。如下所示,这一drawString方法,利用了说明的x,y参数,使你在屏幕上的这一位置,显示一个字符串。
drawString(String str, int x, int y);
To display a Stringobject at the correct location, you must understand the meaning of each of thedrawString parameters. The drawString method x parameter specifies the positionof the String objects left side. The y parameter controls the position of theString objects baseline. For instance, if you try to position the String atlocation (0,0), you will find that much of the String is drawn outside of thevisible window. Figure 428 shows the effect of the x and y parameters on stringplacement:
为了在当前位置上显示一个字符串对象,你必须了解drawString方法每一个参数的意义drawString方法的X参数指示了字符串对象的左部边缘的位置,Y参数控制了字符串对象的基准线位置。例如,如果你把字符串试写在(0,0)位置,你就会发现字符串的大部分将落到屏幕上可见窗口的外边。图428显示了x和y参数对字符串布局的影响:
Figure 428 The x-and-y position specifiedin the drawString method.
图428 drawString方法所规定的x与y位置
429Drawing Characters
429画字符
Depending on yourapplets purpose, there will be times when your program works with Stringobjects while, at other times, your program will work with character arrays. Asyou learned in Tip 428, you can display a String objects contents using thedrawString method. To draw a character array, on the other hand, you can usethe Graphics class drawChar method:
根据你的小应用程序的用途的不同,在有的情况下,你的程序要使用字符串对象,而在另一些情况下,则要使用字符数组。正如你在TIP 428中所了解的,你可以利用drawString方法来显示一个字符串对象的内容。反之,为了显示一个字符数组,则你需用Graphics类中的drawChar方法:
drawChar(char data[], int offset, int length,int x, int y);
As you can see,within the drawChar method, you specify the drawing location using the x and yparameters. In addition, using the offset and length parameters, you canspecify the characters in the array that you want to display. The followingprogram, draw_char.java, uses the drawChar method to display the characterarray 1001 Java Tips:
由上可以看出,在drawChar方法中,你用x和y参数来说明要画字符的所在位置,并且,还可以用偏移(offset)和长度两个参数,来说明字符数组中你要画出的是哪些字符。以下draw_char。java程序使用了drawChar方法来显示字符数组"1001 Java Tips":
import java.applet.*;
import java.awt.*;
public class draw_char extends Applet {
final static char mystring[] =
{'1','0','0','1',' ','J','a','v','a',' ','T','i','p','s'};
public void paint(Graphics g)
{
// display entire string
g.drawChars(mystring, 0, mystring.length, 0, 25);
// display the substring "Java"
g.drawChars(mystring, 5, 4, 0, 50);
}
}
As you can see, thepaint function receives as a parameter, the Graphics object g, which containsthe graphics context. Using this object, the function displays characters tothe applet window. As discussed, the graphics context contains such items asthe current font, font size, color, window coordinates, and so on. Figure 429illustrates the programs output within the Java appletviewer.
如你所见到的那样,paint函数把Graphics对象g作为一个参数接收,g包含的内容就是图形的上下文(字符)。使用这一对象,函数就把几个字符显示在小应用程序的窗口中。图形的上下文包括当前字体,字体大小,字的颜色,窗口坐标,等项参数在内。图429说明了在Java小应用程序显示软件中的输出结果:
Figure 429 The output of the draw_char applet.
图429 draw_char 小应用程序的输出
430Setting the Origin with the translate Method
430用translate方法设置原点
As you have learned, Javasdefault origin for graphics operations is the top-left corner of the appletwindow. Using the Graphics class translate method, however, you can repositionJavas graphics origin. The format of the translate method is as follows:
正如你所了解的那样,Java图形操作的缺省原点是在小应用程序窗口的左上角。但是,利用Graphics类的translate(平移)方法,你可以为Java重定图形的原点。translate方法的格式如下:
translate(int x, int y);
For example, the followingstatement moves Javas graphics origin to the x and y coordinates 100,50:
例如,以下语句将Java的图形原点移到了x,y坐标分别为100,50处:g.translate(100, 50);
Figure 430 illustrates theeffect of the previous translate method:
图430说明了以上translate方法的效果:
Figure 430 Translating the origin.
图430 原点的平移
431Drawing a Line
431画直线
Within a Javaapplet that performs graphics operations, you can draw simple and complexgraphics using line-based graphics. To draw a line within the applet window,you can use the Graphics class drawLine method. The format of the drawLinemethod is as follows:
在执行图形操作的Java小应用程序中,你可利用画直线的图形功能来画出各种简单的和复杂的图形。为了在小应用程序窗口中画出一根直线,你可使用Graphics类中的drawLine方法。drawLine方法的格式如下:
drawLine(int x1, int y1, int x2, int y2);
For example, thefollowing paint method uses the drawLine method to draw a line from thecoordinates( 0,0) to coordinates (160,80):
例如, 下面列出的paint方法利用drawLine方法来画一根从坐标(0,0)到坐标(160,80)的直线段.
public void paint(Graphics g)
{
g.drawLine(0, 0, 160, 80);
}
If you place thispaint method within an applet, the applet will draw a line similar to thatshown in Figure 431.
如果你把这一方法放进一个小应用程序中,这一小应用程序将产生如图431所示的一根直线.
Figure 431 A line drawn from (0,0) to (160,80).
图431 画出从(0,0)到(160,80)的一根直线
432Drawing a Rectangle
432画一矩形
In Tip 431, youlearned that using the drawLine method, your applets can draw a line from oneset of coordinates to another. In a similar way, to draw a rectangle on thescreen, you can use the Graphics class drawRect method. The format of thedrawRect is as follows:
在TIP 431中,你已了解了drawLine方法的使用,你的小应用程序可以画一根从一点到另一点的直线。用类似的方法,为了在屏幕上画一个矩形,你可以使用Graphics类的drawRect
方法. drawRect方法的格式如下:
drawRect(int x, int y, int width, intheight);
The x and yparameters specify the location of the top-left corner of the rectangle. Likewise,the width and height parameters specify the rectangles size. For example, thefollowing statements draw a 10x10 rectangle (in pixels relative to the 0,0origin) within the applet window:
其中x和y参数指示了矩形左上角的位置. 而width和height参数则指明了矩形的大小尺寸. 例如,以下语句在小应用程序窗口中画出了一个10x10的矩形(单位是象素),其左上角在原点0,0:
public void paint(Graphics g)
{
g.drawRect(0, 0, 10, 10);
}
433Drawing a Rounded Rectangle
433画一个圆角的矩形
In Tip 432, youlearned how to draw a rectangle with the drawRect method. Depending on yourapplets purpose, there may be times when you will need to display a rectanglethat uses rounded corners. To draw a rectangle with rounded corners, yourprograms can use the drawRoundRect method, as shown:
在TIP 432中,你已经知道怎样用drawRect方法来画一个矩形.根据小应用程序的用途,你有时可能需要显示一个带有圆角的矩形.为了画出一个带有圆角的矩形,你的程续可以使用drawRoundRect方法,如下所示:
drawRoundRect(int x, int y, int width, intheight,
intarcWidth, int arcHeight);
The arcWidth andarcHeight parameters specify the size of the rectangles rounded corners, asshown in Figure 433.1:
这里,参数arcWidth(弧宽)和arcHeight(弧高)用来说明矩形的圆角的大小,如图433.1所示:
For example, thefollowing paint method uses drawRoundRect to draw the rounded rectangle shownin Figure 433.2:
例如,以下paint方法使用drawRoundRect来画一个如图433.2所示的圆角矩形:
public void paint(Graphics g)
{
g.drawRoundRect(0, 0, 160, 80, 50, 25);
}
Figure 433.2 A rectangle with arcWidth of 50 and arcHeight of25.
图433.2 一个带有arcWidth(弧宽)50和arcHeight(弧高)25的圆角矩形
434Drawing a Circle with the drawRoundRect Method
434利用drawRoundRect方法画圆
As you learned inTip 433, you can draw a rectangle with rounded corners using the drawRoundRectmethod. In a similar way, your programs can draw a circle using thedrawRoundRect method. As discussed, the format of the drawRoundRect method isas follows:
正如你在TIP 433中所学到的那样,你的程序可以用drawRoundRect方法来画圆角矩形.但是,利用drawRoundRect这一方法来画出一个圆. drawRoundRect方法的格式和前面讨论过的一样:
drawRoundRect(int x, int y, int width, intheight, int arcWidth, int arcHeight);
To draw a circleusing the drawRoundRect method, you simply specify an arcWidth that is equal tothe arcHeight, as shown:
利用drawRoundRect方法来画圆,你只要把arcWidth(弧宽)和arcHeight(弧高)两个参数的值取得相同就可以了,如:
drawRoundRect(0, 0, 80, 80, 80, 80);
In this case, thedrawRoundRect method will draw a circle with a radius of 40 pixels, as shown inFigure 434.
在这一例子中,drawRoundRect方法将画出一个半径为40(个象素)的圆,如图434所示.
Figure 434 A circle drawn with the drawRoundRect method.
图434 用drawRoundRect方法画出的一个圆
Using a roundedrectangle is just one of the ways to draw a circle; Tip 442 will show a bettersolution using the drawOval method.
利用drawRoundRect方法来画圆,只是画圆的一种方法;TIP 442将介绍一种利用drawOval
方法来画圆的更好的方案.
435Drawing with Colors
435用颜色作图
Unless your Javaprogram will only run on a monochrome monitor, which isnt likely, you will needthe ability to change the programs drawing color. Within your applets, you canuse the Graphics class setColor method to change the current color. Conversely,your applets can use the getColor method to obtain the current color. Java willuse the current color for drawing text, lines, and filling interiors. Thefollowing applet, color_textline.java, illustrates the use of the setColormethod and results in the screen shown in Figure 435.
除非你的Java程序只在单色显示器上运行(这是不太理想的事情),你需要能修改程序,使它能画出带色彩的图形. 在你的小应用程序中, 你可使用Graphics类的setColor方法来改变当前颜色. 反过来,你的小应用程序也可利用getColor方法来得到当前的颜色. Java将利用当前颜色来画线,写文字和填充封闭区域的内部. 以下color_textline.java小应用程序说明了setColor的使用方法以及它在屏幕上的显示结果,如图435所示.
import java.applet.*;
import java.awt.*;
public class color_textline extends Applet {
public void paint(Graphics g)
{
// draw black text
g.setColor(Color.black);
g.drawString("A line of text in black", 5, 30);
// draw red text
g.setColor(Color.red);
g.drawString("A line of text in red", 5, 60);
// draw magenta text
g.setColor(Color.magenta);
g.drawString("A line of text in magenta", 5, 90);
}
}
Figure 435 Text (and) lines drawn with different colors.
图435 用不同颜色画出的文本行
436Using Predefined Colors
436使用预定义的颜色
In Tip 435, youlearned how to use the Graphics class setColor method to set the current color.When you use the setColor method, you can use the following color constants:
在TIP 435中,你已了解怎样利用Graphics类的setColor方法来设置当前颜色. 当你使用setColor方法时,你可以利用下列颜色常量:
l black黑
l blue蓝
l cyan青
l darkGray深灰
l gray灰
l green绿
l lightGray亮灰
l magenta紫红
l orange橙
l pink淡红
l red红
l white白
l yellow黄
For example, thefollowing program, ColorConstants.java, illustrates the use of several colorconstants within the setColor method:
以下的ColorConstants.java程序说明了怎样利用setColor方法来使用颜色常量:
import java.applet.*;
import java.awt.*;
public class ColorConstants extends Applet {
public void paint(Graphics g)
{
g.setColor(Color.yellow);
g.drawString("Yellow Yellow Yellow", 5, 30);
g.setColor(Color.blue);
g.drawString("Blue Blue Blue", 5, 60);
g.setColor(Color.green);
g.drawString("Green Green Green", 5, 90);
}
}
437Creating a New Color
437创建新的颜色
As you learned inTip 436, Java provides several predefined color values. However, depending onyour programs purpose, there may be times when you need a color outside ofJavas predefined colors. In such cases, you can create any color you want usingthe Graphics class Color constructors, as shown:
正如你在TIP 436中所了解的那样,Java提供了几种已经预先定义好的颜色值. 但是,根据你的程序的不同用途,你有时可能需要一种在Java预定义范围之外的颜色. 在这种情况下,你可利用Graphics类的颜色构造函数Color constructors来创建任何一种你所想要的颜色,例如:
Color(int r, int g, int b);
Color(int rgb);
Color(float r, float g, float b);
The followingapplet, rgb_shades.java, illustrates the use of the Graphics classColorconstructor by creating eight different shades of red, green, and blue, asshown in Figure 437.
下面的rgb_shades.java小应用程序说明了Graphics类的颜色构造函数Color constructors的用法,如图437所示,这里是利用红,绿,蓝三种基色的不同色调(shade)的混合来创建
8种不同颜色的.
import java.applet.*;
import java.awt.*;
public class rgb_shades extends Applet {
public void paint(Graphics g)
{
// shades of red
for(int i=1; i<=8; i++)
{
Color color = new Color(i*32 -1, 0, 0);
g.setColor(color);
g.fillRect(i*30 + 2, 2, 28, 28);
}
// shades of green
for(int i=1; i<=8; i++)
{
Color color = new Color(0, i*32 - 1, 0);
g.setColor(color);
g.fillRect(i*30 + 2, 32, 28, 28);
}
// shades of blue
for(int i=1; i<=8; i++)
{
Color color = new Color(0, 0, i*32 - 1);
g.setColor(color);
g.fillRect(i*30 + 2, 62, 28, 28);
}
}
}
Figure 437 Applet illustrating the use of the Color constructor.
图437 说明色彩构造函数Color constructors用法的小应用程序
438Changing the Default Applet Background
438改变小应用程序的缺省背景颜色
Each of theprevious Java applets in this section have used the same (default) backgroundcolor. By default, Java uses a light gray background color for the Windows 95and Windows NT appletviewer. Using the Component class setBackground method,you can change the background color. Your applets can use the Component classmethods because Applet is a subclass of the Component class. The followingapplet, background.java, changes the background color to black, as shown inFigure 438.
本节前面的每一个小应用程序都用了同一种缺省背景颜色. 根据缺省,Java在Windows 95和Windows NT的小应用程序观察器(appletviewer)中使用了亮灰色的背景颜色. 利用成份类(Component class)中的设置背景方法(setBackground method), 你可以改变背景的颜色. 你的小应用程序可以使用Component类中的方法是因为小应用程序是Component类的一个子类. 以下的background.java小应用程序把背景的颜色改成了黑色,如图438所示.
import java.applet.*;
import java.awt.*;
public class background extends Applet {
public void init()
{
setBackground(Color.black);
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.drawString("White text on black background", 5, 50);
}
}
figure 438 An applet illustrating the use of the setBackground method.
图438 说明setBackground使用方法的小应用程序
439Drawing a Filled Rectangle
439画一个填充颜色的矩形
As you learned inTip 432, you can draw a rectangle using the Graphics class drawRect method. Asyou also learned, the drawRect method draws an empty rectangle. Depending onyour applets purpose, there may be times when you will need to draw a filledrectangle. To draw a rectangle with a filled interior, your applets can use theGraphics class fillRect method. The format of the fillRect method is asfollows:
正如你在TIP 432中所了解的,你可以用Graphics类的drawRect方法来画一个矩形. 你也知道了,drawRect方法画的是一个空心的矩形. 根据你的小应用程序的用途,你有时可能需要画一个填色矩形. 为了画一个内部填色的矩形,你的小应用程序可以使用Graphics类中的fillRect方法. fillRect方法的以下的格式如下所示:
fillRect(int x, int y, int width, intheight);
The fillRect methodis similar to the drawRect method in that the x and y parameters specify thelocation of the rectangles top-left corner; the width and height parameterspecify the rectangles dimension. When you draw a filled rectangle, Java usesthe color defined by the setColor method.
FillRect方法和drawRect方法在参数意义的说明上是类似的,即x,y代表矩形的左上角位置,wifth和height则用来指定矩形的大小尺寸. 当你画填色矩形时,Java用setColor方法定义的颜色来画此矩形.
440Drawing a Filled Rounded Rectangle
440画一个填充颜色的圆角矩形
As you have learnedin Tip 439, you can draw a filled rectangle using the fillRect method. Just asthe Graphics class drawRoundRect method lets you draw a rounded rectangle, yourapplets can use the fillRoundRect method to draw a filled rectangle. The formatof the fillRoundRect method is as follows:
正如你在TIP 439中所了解的,你可以用fillRect方法画一个填充颜色的矩形. 也正如drawRoundRect方法让你画一圆角矩形那样,你的小应用程序时可以用fillRoundRect方法画一个填色圆角矩形. 填色圆角矩形的方法fillRoundRect的格式如下:
fillRoundRect(int x, int y, int width, intheight,
intarcWidth, int arcHeight);
The following paintmethod illustrates the use of the fillRoundRect method to draw the filledrectangle shown in Figure 440. As is the case with the Graphics class fillRectmethod, the fillRoundRect method uses the color defined by the setColor method:
以下的paint方法说明了怎样利用fillRoundRect方法来画如图440所示的填色圆角矩形.和Graphics类fillRect方法一样,fillRoundRect方法使用了由setColor方法所定义的颜色:
public void paint(Graphics g)
{
g.fillRoundRect(0, 0, 160, 80, 50, 25);
}
Figure 440 A filled rectangle with arcWidth of 50 andarcHeight of 25.
图440 一个arcWidth为50而arcHeight为25的填充颜色的圆角矩形
441Building a Simple Bar Chart
441建立一个简单的BarChart(方块图)
Whether you arewriting a book or a Java-based program, a picture is worth a thousand words.Within your applets, charts provide an effective means for presenting data aspictures. Based on what you have learned from previous tips, you can use theGraphics class drawString, drawLine, and fillRect methods to create a barchart. The following applet, bar_chart.java, will display the bar chart shownin Figure 441.
不管你是在写书或是编程,画一个图会胜过千言万语。在你的小应用程序中,图表(chart)为数据的形象化表示提供了一种有效的方法。根据你在前面的TIP中所学到的,你可以用Graphics类中的drawString,drawLine和fillRect等方法来创建一个bar chart。 以下小应用程序bar_chart.java将在屏幕上显示如图441所示的bar chart.。
import java.applet.*;
import java.awt.*;
public class bar_chart extends Applet {
final static int data_set[] = { 50, 85, 32, 65 };
final static String data_label[] = { "93", "94","95", "96" };
intGraph_offset = 20; // graphoffset from origin
intGraph_Height = 150;
intY_Tick_Height = Graph_Height / 5; // 5 Y-axis divisions;
intGraph_Width = 240;
intX_Tick_Width = Graph_Width / data_set.length; // 4 X-axis
// divisions
public void paint(Graphics g)
{
g.setColor(Color.black);
// draw y axis
g.drawLine(Graph_offset + Graph_Width, Graph_offset,
Graph_offset + Graph_Width, Graph_offset + Graph_Height);
// draw y-tick labels
for(int i=0; i<=5; i++)
{
g.drawString(String.valueOf(i*20), // 20 units per tick
Graph_offset + Graph_Width + 10,
Graph_offset + Graph_Height -(i*Y_Tick_Height));
// draw grid line
g.drawLine(Graph_offset,
Graph_offset + Graph_Height -(i*Y_Tick_Height),
Graph_offset + Graph_Width + 5,
Graph_offset + Graph_Height-(i*Y_Tick_Height));
}
// draw x axis
g.drawLine(Graph_offset, Graph_offset + Graph_Height,
Graph_offset + Graph_Width,Graph_offset +
Graph_Height);
// draw x-tick lables
for(int i=0; i<data_set.length; i++)
{
g.drawString(data_label[i],
Graph_offset + X_Tick_Width*i + X_Tick_Width/2,
Graph_offset + Graph_Height + 20);
// draw x-tick lines
g.drawLine(Graph_offset + X_Tick_Width*i +
X_Tick_Width/2,
Graph_offset + Graph_Height,
Graph_offset + X_Tick_Width*i +X_Tick_Width/2,
Graph_offset + Graph_Height +5);
}
// draw data(bar lines)
g.setColor(Color.red);
for(int i=0; i<data_set.length; i++)
{
int bar_height = data_set[i] * Graph_Height / 100;
g.fillRect(Graph_offset + X_Tick_Width*i +
X_Tick_Width/4,
Graph_offset + Graph_Height - bar_height,
X_Tick_Width/2, bar_height);
}
}
}
Figure 441 Bar Chart applet.
图441 Bar Chart 小应用程序
442Drawing an Oval
442画一卵圆形
Within yourapplets, there will be times when you need to draw ovals and circles. To drawan oval, your programs can use the Graphics class drawOval method. The formatof the drawOval method is as follows:
在你的小应用程序中,有的情况下你会需要画一个卵圆形和圆形.为了画一个卵圆形你可以利用Graphics类中的drawOval方法. drawOval方法的格式如下:
drawOval(int x, int y, int width, intheight);
For example, thefollowing paint method uses the drawOval class to draw an oval with dimensionsof 90 x 60 pixels at location(0,0), as shown in Figure 442.
例如,以下这个paint方法利用drawOval在(0,0)位置画了一个大小为90 x 60 象素,如图442所示的卵圆:
public void paint(Graphics g)
{
g.drawOval(0, 0, 90, 60);
}
Figure 442 A 90 x 60 pixels oval at location (0,0).
图442 一个在(0,0)位置大小为90 X 60个象素的卵圆
443Drawing a Circle Using the drawoval() Method
443利用drawoval方法画一个圆
In Tip 434, youlearned how to draw a circle using arectangle with rounded corners. A better way to draw circles, however, is touse the drawOval method with equal width and height. For example, the followingstatement uses the drawOval method to draw a circle with a diameter of 100pixels:
你在TIP 434中已了解怎样用画圆角矩形的方法来画一个圆. 但是,画圆的一个更好的办法是利用drawOval方法并让其中宽和高的参数相同. 例如,以下语句利用drawOval方法画出了一个半径为100个象素的圆.
drawOval(0, 0, 100, 100);
444Drawing a Filled Oval
444画填色卵圆
As you learned inTip 443, your applets can draw an oval using the drawOval method. As you havealso learned, the drawOval method draws an empty oval. Depending on yourapplets purpose, you may want to draw a filled oval. In such cases, yourprograms can use the fillOval method. The format of the fillOval method is asfollows:
正如你在TIP 443中所了解的,你在小应用程序可以用drawOval方法来画一个卵圆. 你也看到了利用drawOval方法画出的是一个空心卵圆. 根据你的小应用程序的用途,你有时可能需要画一个填色的卵圆.在这种情况下,你的程序可以利用fillOval方法. FillOval方法的格式如下:
fillOval(int x, int y, int width, intheight);
The fillOval methoduses the color specified by the setColor method. The following applet,fill_oval.java, use the fillOval method to draw several filled ovals of varioussizes and shapes, as shown in Figure 444:
FillOval方法填充所用的颜色由setColor方法指定.以下的小应用程序fill_oval.java利用fillOval方法画出了几个大小和形状不同的填色卵圆,如图444所示.
import java.applet.*;
import java.awt.*;
public class fill_oval extends Applet {
public void paint(Graphics g)
{
g.fillOval(0, 30, 50, 20);
g.fillOval(70, 0, 20, 80);
g.fillOval(140, 0, 75, 75);
}
}
Figure 444 Several filled ovals drawn with the fillOvalmethod.
图444 利用fillOval方法画出的几个填色卵圆
445Drawing an Arc
445画一段弧
When your programsperform graphics operations, there may be times when you need to draw an arc.In such cases, your programs can use the Graphics class drawArc method. Theformat of the drawArc method is as follows:
当你的程序执形图形操作时,有时你会需要画一个弧. 在这种情况下,你可利用Graphics类中的drawArc方法. drawArc方法的格式如下:
drawArc(int x, int y, int width, int height,int startAngle, int arcAngle);
Figure 445.1 showshow the methods width, height, startAngle, and arcAngle parameters control theshape of the arc:
图445.1说明了怎样利用width(宽度), height(高度), startAngle(起始角)和arcAngle(圆弧四个参数来控制所画圆弧的形状.
Figure 445.1 Parameters of the drawArcmethod.
图445.1 drawArc方法的几个参数
The followingprogram illustrates the use of the drawArc method. Figure 445.2 illustrates theprograms output:
以下程序说明了drawArc方法的使用规则,图445.2是该程序的输出:
import java.applet.*;
import java.awt.*;
public class draw_arc extends Applet {
public void paint(Graphics g)
{
g.drawArc(10, 20, 50, 30,30, 90);
g.drawArc(80, 10, 30, 80, 0, 135);
g.drawArc(150, 10, 60, 60, 120,300);
}
}
Figure 445.2 A series of arcs drawn by the drawArc method.
图445.2 由drawArc方法画出的一系列圆弧
446Drawing a Filled Arc
446画一填色的圆弧(弓)
As you learned inTip 445, your programs can draw an arc using the Graphics class drawArc method.Depending on your applets purpose, you may want to draw a filled arc. In suchcases, your programs can use the fillArc method. The format of the fillArcmethod is as follows:
正如你在TIP 445所了解的那样,你的程序可利用Graphics类中的drawArc方法来画一个圆弧.根据你的小应用程序的用途的不同,你的程序有时会想要画一个填充颜色的圆弧.在这情况下,你的程序可利用fillArc方法. fillArc方法的格式如下:
fillArc(intx, int y, int width, int height, int startAngle, int arcAngle);
The fillArc methoduses the color specified by the setColor method. The following applet,fill_arc.java, draws several filled arcs of various sizes and shapes, as shownin Figure xxx:
illArc方法填充所用的颜色由setColor方法指定.以下的小应用程序fill_arc.java画出了几个大小和形状不同的填色圆弧,如图446所示.
import java.applet.*;
import java.awt.*;
public class fill_arc extends Applet {
public void paint(Graphics g) {
g.fillArc(10, 20, 50, 30,30, 90);
g.fillArc(80, 10, 30, 80, 0, 135);
g.fillArc(150, 10, 60, 60, 120,300);
}
}
Figure 446 Several filled arcs drawn with the fillArcmethod.
图446 由fillArc方法画出的一系列填色的圆弧
447Drawing a Pie Chart
447画一个饼图
Tipnumber
In Tip 446, youlearned how to draw filled arcs using the Graphics class fillArc method.Likewise, in Tip 441, you learned how to draw bar codes. In a similar way, byusing pie-shaped filled arcs, your programs can create pie charts. Thefollowing applet, pie_chart.java, displays the chart shown in Figure 447.
在TIP 446中已学过了怎样用Graphics类中的fillArc方法画各种填色的圆弧.在TIP 441中你也知道了怎样画方块图. 与此类似,利用pie形的填色圆弧,你的程序可以建立一个pie图(饼图).以下的小应用程序,pie_chart.java,能产生如图447所示的饼图.
import java.applet.*;
import java.awt.*;
public class pie_chart extends Applet {
final static int data_set[] = { 20, 40, 32, 8 };
final static String data_label[] =
{"Apple","Orange","Banana","Other"};
final static Color data_color[] =
{Color.red, Color.blue, Color.yellow, Color.green};
intGraph_offset = 20; // Graph offsetfrom origin
intGraph_Diameter = 150;
public void paint(Graphics g)
{
int start_angle, pie_size;
int sub_total = 0;
start_angle = 0;
for(int i=0; i < data_set.length; i++)
{
// draw pie
sub_total += data_set[i];
pie_size = sub_total * 360 / 100 - start_angle;
g.setColor(data_color[i]);
g.fillArc(Graph_offset, Graph_offset, Graph_Diameter,
Graph_Diameter,start_angle, pie_size);
start_angle += pie_size;
// draw legend
g.fillRect(Graph_offset + Graph_Diameter + 10,
Graph_offset + i * 20,15, 15);
g.setColor(Color.black);
g.drawString(data_label[i], Graph_offset +
Graph_Diameter + 10 +20,
Graph_offset + i * 20 +15);
}
}
}
Figure 447 Pie chart applet.
图447 画饼图的小应用程序
448Drawing a Polygon
448画一多边形
A polygon is aclosed plane figure bounded by straight lines. As the graphics your applet mustdraw become more complex, there may be times when you can represent the shapeas a polygon. Graphics-based programs normally represent a polygon using twoarrays. One array contains the polygons x coordinates, while the second arraycontains the y coordinates. To draw a polygon within your applet, you can usethe Graphics class drawPolygon method. The formats for the drawPolygon methodare as follows:
多边形就是平面上由一些直线段围成的封闭图形. 当你的小应用程序所画的图形变得更复杂时,你有时可以将它的形状表示成为一个多边形. 基于图形的程序通常用两个维数组来表示一个多边形. 其中一个数组包含多边形的X坐标,而另一个数组包含多边形的Y坐标.为了在你的小应用程序中画一个多边形,你可使用Graphics类的drawPolygon方法.drawPolygon方法的格式如下:
drawPolygon(int xPoints[], int yPoints[], intnPoints);
drawPolygon(Polygon p);
Be aware that Javadoes not close off the polygon automatically. To draw a closed polygon, thelast point in the polygon must be the same as the first point. The followingapplet, draw_poly.java, uses the drawPolygon method to draw several polygons,as shown in Figure 448:
注意,Java不能自动封闭一个多边形. 为了画出一个封闭多边形,多边形的最后一点的坐标必须与第一个点的坐标相同. 以下小应用程序draw_poly.java利用drawPolygon方法画了几个多边形,如图448所示.
import java.applet.*;
import java.awt.*;
public class draw_poly extends Applet {
intpoly1_x[] = { 40, 80, 0, 40};
intpoly1_y[] = { 5, 45, 45, 5};
intpoly2_x[] = { 140, 180, 180, 140, 100, 100, 140};
intpoly2_y[] = { 5, 25, 45, 65, 45, 25, 5};
intpoly3_x[] = { 240, 260, 220, 260, 220, 240};
intpoly3_y[] = { 5, 65, 85, 25, 25, 5};
public void paint(Graphics g)
{
g.drawPolygon(poly1_x, poly1_y, poly1_x.length);
g.drawPolygon(poly2_x, poly2_y, poly2_x.length);
g.drawPolygon(poly3_x, poly3_y, poly3_x.length);
}
}
Figure 448 Polygons drawn using the drawPolygon() method.
图448 利用drawPolygon()方法画的多边形
449Drawing a Filled Polygon
448画一填色多边形
In Tip 448, youlearned how to draw polygons using the Graphics class drawPolygon method. In asimilar way, your applets can draw filled polygons using the fillPolygonmethod. Unlike the drawPolygon method, the fillPolygon method willautomatically close off the end of the polygon, even if the last point is notthe same as the first point. The fillPolygon method uses the color specified bythe setColor method. The following program, fill_poly.java, uses thefillPolygon method to draw the filled polygons, as shown in Figure 449:
在TIP 448中你已指道了怎样用Graphics类中的drawPolygon方法画多边形.与此类似,你的小应用程序可以利用fillPolygon方法来画填色的多边形. 和drawPolygon方法不同,fillPolygon方法能自动封闭多边形,即使它的最后一个顶点坐标和第一个顶点的坐标不相同. 以下的程序fill_poly.java使用fillPolygon方法画出了如图449所示的一些填色的多边形.
import java.applet.*;
import java.awt.*;
public class fill_poly extends Applet {
int poly1_x[] = { 40, 80, 0, 40};
int poly1_y[] = { 5, 45, 45, 5};
int poly2_x[] = { 140, 180, 180, 140, 100, 100, 140};
int poly2_y[] = { 5, 25, 45, 65, 45, 25, 5};
int poly3_x[] = { 240, 260, 220, 260, 220, 240};
int poly3_y[] = { 5, 65, 85, 25, 25, 5};
public void paint(Graphics g)
{
g.fillPolygon(poly1_x, poly1_y, poly1_x.length);
g.fillPolygon(poly2_x, poly2_y, poly2_x.length);
g.fillPolygon(poly3_x, poly3_y, poly3_x.length);
}
}
Figure 449 Filled polygons drawn usingthe fillPolygon method.
图449 利用fillPolygon方法画出的一些填色多边形
连载1(TIP:424-449)完
连载2(TIP“450-478)