Java教程-在Applet中显示图形
在Applet中显示图形
java.awt.Graphics类提供了许多用于图形编程的方法。
Graphics类的常用方法:
- public abstract void drawString(String str, int x, int y):用于绘制指定的字符串。
- public void drawRect(int x, int y, int width, int height):绘制具有指定宽度和高度的矩形。
- public abstract void fillRect(int x, int y, int width, int height):用默认颜色填充具有指定宽度和高度的矩形。
- public abstract void drawOval(int x, int y, int width, int height):绘制具有指定宽度和高度的椭圆。
- public abstract void fillOval(int x, int y, int width, int height):用默认颜色填充具有指定宽度和高度的椭圆。
- public abstract void drawLine(int x1, int y1, int x2, int y2):在点(x1, y1)和(x2, y2)之间绘制线条。
- public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):绘制指定的图像。
- public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle):绘制圆弧或椭圆弧。
- public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle):填充圆弧或椭圆弧。
- public abstract void setColor(Color c):将图形的当前颜色设置为指定的颜色。
- public abstract void setFont(Font font):将图形的当前字体设置为指定的字体。
Applet中的图形示例:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>