java applet
先简单介绍一下啥子是java applet,
Applet是一种特殊的Java程序,它本身不能单独运行,需要嵌入在一个HTML文件中,借助浏览器或Appletviewer来解释执行.Applet可能通过网络传输,由浏览器自动装载并执
行.
和Applicaton不同,Applet程序都必须继承自Java的Java.applet.Applet类或javax.swing.JApplet类 public class myApplet extends java.applet.Applet或public class
myApplet extends javax.swing.JApplet 其实 JApplet类也是继承自Applet类. 要浏览Applet需要将它嵌入在网页中,只需在HTML文件中插入<APPLET>标记即可.
1.Applet的使用
import java.applet.Applet; import java.awt.Graphics; public class AppletDemo extends Applet { @Override public void paint(Graphics g) { g.drawString("Hello Applet!", 5, 30);//绘制文本 g.drawArc(80,50,40,40,20,360);//绘制一个圆形 } }
2.Applet程序HTML文件的编写
<html> <head> <title>Applet</title> </head> <body> <applet CODE = "AppletDemo.class" width = "300" height = "100"></applet> </body> <html>
3.Applet常用方法
import java.applet.Applet; import java.awt.Graphics; public class AppletDemo extends Applet { String mystring = ""; @Override public void paint(Graphics g) { g.drawString(mystring, 5, 30); } public void init() { mystring = mystring + "正在初始化..."; repaint(); } public void start() { mystring = mystring + "正在开始启动程序..."; repaint(); } public void stop() { mystring = mystring + "正在停止执行程序..."; repaint(); } public void destroy() { mystring = mystring + "正在回收资源..."; repaint(); } }
4.从HTML文件向Java小程序传递参数
传递的参数必须在HTML文件中声明,并且在Applet初始化时进行读取。参数使用<applet>标签的子标签<param>声明,且不需要结束标签。
<param name=param_name value=param_value>
<html> <head><title>Parameters</title></head> <body> This is a message.<br> <applet code=”ParamPass.class” width=”400” height=”100”> <param name=”fontname” value=”DialogInput” /> <param name=”fontsize” value=”24” /> </applet> </body></html>
import java.awt.Font; 2 import java.awt.Graphics; 3 import javax.swing.JApplet; 4 import javax.swing.JPanel; 5 6 public class ParamPass extends JApplet 7 { 8 private Font f; 9 private int size; 10 private String name; 11 public void init() 12 { 13 name = getParameter("fontname"); 14 size = Integer.parseInt(getParameter("fontsize")); 15 f = new Font(name,Font.BOLD,size); 16 add(new MyPanel()); 17 } 18 class MyPanel extends JPanel 19 { 20 public void paintComponent(Graphics g) 21 { 22 super.paintComponent(g); 23 g.setFont(f); 24 g.drawString("This is a message.", 50, 50); 25 } 26 } 27 }
以上内容仅仅是对Applet的相关概念、使用Applet程序的基本方法以及在HTML代码中嵌入Applet程序等基础的内容的了解。