第 12章 Applet及绘图
12.1 applet小应用程序
12.2 Java applet与 applection
12.3 绘制几何图形
12.4 字体和颜色
12.5 习题
12.1 applet小应用程序
12.1.1 Applet类
12.1.2 JApplet类
12.1.3 向 applet传递参数
12.1.1 Applet类
start()
stop() destroy()
init()
重载离开当前页 返回当前页退出初始化 启动中止 销毁
12.1.2 JApplet类
applet程序应直接继承于 JApplet。 JApplet是
Applet的子类,其对象属于 Swing组件。
applet程序的字节码文件应嵌入网页。
例 12-1 applet程序源代码 运 行
12.1.3 向 applet传递参数
在 HTML文件向 applet传递参数:
<PARAM NAME=parametername
VALUE=parametervalue>
在 applet中调用下述方法读取:
public String getParameter(String name)
例 12-2 向 applet传递参数源代码 运 行
12.2 Java applet与 application
applet与 application的不同:
– 每次运行 applet时都必须下载所有的相关文件,因此显示某些 applet时可能需要花不少的时间。
– 为了保证网页运行的安全,applet无法访问本地文件。除非它通过了,数字签名,。
12.2 Java applet与 application(续)
Java applet与 application之间大多可以相互转换,不过,编写一个既可作为 applet运行,又可作为 application运行的程序或许更有实际意义。一般来说,编写这样的程序并不难。
例 12-3 程序作为 applet和 application运行源代码 运 行
12.3 绘制几何图形
12.3.1 以面板作为画布
12.3.2 绘制基本几何图形
– 绘制字符串
– 绘制直线
– 绘制矩形
– 绘制椭圆
– 绘制圆弧
– 绘制多边形
12.3.1 以面板作为画布
要在面板上绘图,需要定义一个继承于
JPanel的新类,并覆盖其中的下述方法:
protected void
paintComponent(Graphics g)
12.3.2 绘制基本几何图形
绘制字符串,
drawString(String str,int x,int y)
12.3.2 绘制基本几何图形(续)
绘制直线:
drawLine(int x1,int y1,int x2,int y2)
12.3.2 绘制基本几何图形(续)
绘制矩形:
drawRect(int x,int y,int width,int height)
fillRect(int x,int y,int width,int height)
drawRoundRect(int x,int y,int width,int
height,int arcWidth,int arcHeight)
fillRoundRect(int x,int y,int width,int
height,int arcWidth,int arcHeight)
draw3DRect(int x,int y,int width,int height,
boolean raised)
fill3DRect(int x,int y,int width,int height,
boolean raised)
12.3.2 绘制基本几何图形(续)
绘制椭圆:
drawOval(int x,int y,int width,int
height)
fillOval(int x,int y,int width,int
height)
12.3.2 绘制基本几何图形(续)
绘制圆弧:
drawArc(int x,int y,int width,int
height,int startAngle,
int arcAngle)
fillArc(int x,int y,int width,int
height,int startAngle,
int arcAngle)
12.3.2 绘制基本几何图形(续)
绘制多边形:
drawPolygon(int[] xPoints,int[]
yPoints,int nPoints)
fillPolygon(int[] xPoints,int[]
yPoints,int nPoints)
12.3.2 绘制基本几何图形(续)
Java语言中,组件的坐标系统以 x表示水平轴,
y表示垂直轴,原点在组件的左上角,x轴向右为正方向,y轴向下为正方向,单位为像素。
例 12-4 绘制基本几何图形源代码 运 行
12.4 字体和颜色
12.4.1 字体
12.4.2 颜色
12.4.1 字体
Font(字体)的构造方法:
public Font(String name,int
style,int size)
例:
Font f=new Font(“DialogInput”,
Font.BOLD+Font.ITALIC,12);
12.4.1 字体(续)
设置字体:
– 为组件设置字体:
例:
Font f=new Font(“DialogInput”,
Font.BOLD+Font.ITALIC,12);
JTextField tf=new JTextField();
tf.setFont(f);
– 为当前所画对象设置字体:
例:
g.setFont(f);
12.4.1 字体(续)
GraphicsEnvironment
– getLocalGraphicsEnvironment()
– getAvailableFontFamilyNames()
例 12-5 设置字体源代码 运 行
12.4.2 颜色
Color(颜色)的构造方法:
public Color(int r,int g,int b)
Color类中的标准颜色静态常量:
– BLACK,BLUE,CYAN,DARK_GRAY,GRAY、
GREEN,LIGHT_GRAY,MAGENTA,ORANGE、
PINK,RED,WHITE,YELLOW
12.4.2 颜色(续)
设置颜色:
– 为组件设置颜色:
例:
JTextField tf=new JTextField();
tf,setBackground(Color.YELLOW);
tf,setForeground(Color.RED);
– 为当前所画对象设置颜色:
例:
g.setColor(Color.RED)
例 12-6 设置颜色源代码 运 行
12.5 习 题