本节中,我们将创建一个小应用程序,它使用循环生成其图案。我们将使用if语句和setColor方法。同时我们将介绍drawString方法,并使用它在小应用程序窗口中写出文本。
下面的小应用程序是显示一串七个面孔,我们下面来看看效果。
先贴上自己慢慢敲的一个小时的代码:
package 一个事例图形小应用程序;
import javax.swing.JApplet;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
//Graphics and Color public class differentFace extends JApplet
{
public static final int FACE_DIAMETER = 50;
public static final int X_FACEO = 10;
public static final int Y_FACEO = 5; public static final int EYE_WIDTH = 5;
public static final int EYE_HIGHT = 10;
public static final int X_RIGHT_EYEO = 20;
public static final int Y_RIGHT_EYEO = 15;
public static final int X_LEFT_EYEO = 45;
public static final int Y_LEFT_EYEO = Y_RIGHT_EYEO; public static final int NOSE_DIAMETER = 5;
public static final int X_NOSEO = 32;
public static final int Y_NOSEO = 25; public static final int MOUTH_WIDTH = 30;
public static final int MOUTH_HEIGHTO = 0;
public static final int X_MOUTHO = 20;
public static final int Y_MOUTHO = 35;
public static final int MOUTH_START_ANGLE = 180;
public static final int MOUTH_EXTENT_ANGLE = 180; public void paint(Graphics canvas){
int i,xOffset,yOffset;//希望循环结束后i的值还是要存在
for(i = 0; i <= 4; i++){
//画出一张脸
xOffset = 50 * i;
yOffset = 30 * i; if(i%2==0){
canvas.setColor(Color.LIGHT_GRAY);
canvas.fillOval(X_FACEO + xOffset, Y_FACEO + 30 * i, FACE_DIAMETER,FACE_DIAMETER);
}
canvas.setColor(Color.BLACK);
canvas.drawOval(X_FACEO + xOffset, Y_FACEO + yOffset, FACE_DIAMETER, FACE_DIAMETER);
//画出眼睛
canvas.setColor(Color.BLACK);
canvas.fillOval(X_RIGHT_EYEO + xOffset, yOffset + Y_RIGHT_EYEO, EYE_WIDTH, EYE_HIGHT);
canvas.fillOval(X_LEFT_EYEO + xOffset, yOffset + Y_LEFT_EYEO, EYE_WIDTH, EYE_HIGHT);
//画鼻子
canvas.setColor(Color.black);
canvas.fillOval(X_NOSEO + xOffset, Y_NOSEO + yOffset, NOSE_DIAMETER, NOSE_DIAMETER );
//画嘴巴
canvas.setColor(Color.black);
canvas.drawArc(X_MOUTHO + xOffset, Y_MOUTHO + yOffset, MOUTH_WIDTH, MOUTH_HEIGHTO + 3 * i, MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE); }
//循环结束后i的值为5
xOffset = 50 * i;
yOffset = 30 * i;
canvas.setColor(Color.BLACK);
canvas.drawOval(X_FACEO + xOffset, Y_FACEO + yOffset,FACE_DIAMETER,FACE_DIAMETER);
canvas.drawString("zhangjie is a hardworking boy", X_FACEO+xOffset+FACE_DIAMETER, Y_FACEO+yOffset);
} }
代码太长,接着敲下去也没有什么意义了,还是先来分析分析代码。
最后的效果是没有显现出来的,drawString方法,它是会在笑脸的上方显示出文字的效果
还是先来简单的介绍一下drawString方法,它类似于绘制椭圆的方法,但是它的作用是用来显示文字而不是绘制图形。例如将hello显示在点(10,20)的位置:
canvas.drawString("hello",10,20);