标签:style blog color java 使用 os for ar
本届中,我们将创建一个小应用程序,它使用循环生成其图案。我们将使用if语句和setColor方法。同时我们将介绍drawString方法,并使用它在小应用程序窗口中写出文本。
下面的小应用程序是显示一串七个面孔,我们下面来看看效果。
先贴上自己慢慢敲的一个小时的代码:
1 package 一个事例图形小应用程序; 2 import javax.swing.JApplet; 3 import java.awt.*; 4 import java.awt.Color; 5 import java.awt.Graphics; 6 //Graphics and Color 7 8 public class differentFace extends JApplet 9 { 10 public static final int FACE_DIAMETER = 50; 11 public static final int X_FACEO = 10; 12 public static final int Y_FACEO = 5; 13 14 public static final int EYE_WIDTH = 5; 15 public static final int EYE_HIGHT = 10; 16 public static final int X_RIGHT_EYEO = 20; 17 public static final int Y_RIGHT_EYEO = 15; 18 public static final int X_LEFT_EYEO = 45; 19 public static final int Y_LEFT_EYEO = Y_RIGHT_EYEO; 20 21 public static final int NOSE_DIAMETER = 5; 22 public static final int X_NOSEO = 32; 23 public static final int Y_NOSEO = 25; 24 25 public static final int MOUTH_WIDTH = 30; 26 public static final int MOUTH_HEIGHTO = 0; 27 public static final int X_MOUTHO = 20; 28 public static final int Y_MOUTHO = 35; 29 public static final int MOUTH_START_ANGLE = 180; 30 public static final int MOUTH_EXTENT_ANGLE = 180; 31 32 public void paint(Graphics canvas){ 33 int i,xOffset,yOffset;//希望循环结束后i的值还是要存在 34 for(i = 0; i <= 4; i++){ 35 //画出一张脸 36 xOffset = 50 * i; 37 yOffset = 30 * i; 38 39 if(i%2==0){ 40 canvas.setColor(Color.LIGHT_GRAY); 41 canvas.fillOval(X_FACEO + xOffset, Y_FACEO + 30 * i, FACE_DIAMETER,FACE_DIAMETER); 42 } 43 canvas.setColor(Color.BLACK); 44 canvas.drawOval(X_FACEO + xOffset, Y_FACEO + yOffset, FACE_DIAMETER, FACE_DIAMETER); 45 //画出眼睛 46 canvas.setColor(Color.BLACK); 47 canvas.fillOval(X_RIGHT_EYEO + xOffset, yOffset + Y_RIGHT_EYEO, EYE_WIDTH, EYE_HIGHT); 48 canvas.fillOval(X_LEFT_EYEO + xOffset, yOffset + Y_LEFT_EYEO, EYE_WIDTH, EYE_HIGHT); 49 //画鼻子 50 canvas.setColor(Color.black); 51 canvas.fillOval(X_NOSEO + xOffset, Y_NOSEO + yOffset, NOSE_DIAMETER, NOSE_DIAMETER ); 52 //画嘴巴 53 canvas.setColor(Color.black); 54 canvas.drawArc(X_MOUTHO + xOffset, Y_MOUTHO + yOffset, MOUTH_WIDTH, MOUTH_HEIGHTO + 3 * i, MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE); 55 56 } 57 //循环结束后i的值为5 58 xOffset = 50 * i; 59 yOffset = 30 * i; 60 canvas.setColor(Color.BLACK); 61 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);
62 } 63 64 }
代码太长,接着敲下去也没有什么意义了,还是先来分析分析代码。
最后的效果是没有显现出来的,drawString方法,它是会在笑脸的上方显示出文字的效果
还是先来简单的介绍一下drawString方法,它类似于绘制椭圆的方法,但是它的作用是用来显示文字而不是绘制图形。例如将hello显示在点(10,20)的位置:
canvas.drawString("hello",10,20);
java工程开发之图形化界面之(第四课),布布扣,bubuko.com
标签:style blog color java 使用 os for ar
原文地址:http://www.cnblogs.com/tianxia2s/p/3928692.html