简单Java Applet示例

下午看到一个涉及到Java Applet的问题,发现自己已经都不知道多少年没接触Applet了,稍微看一下,运行了个简单示例。

JDK8 – Java Applets

A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment.

Swing provides a special subclass of the Applet class called javax.swing.JApplet. The JApplet class should be used for all applets that use Swing components to construct their graphical user interfaces (GUIs).

The browser’s Java Plug-in software manages the lifecycle of an applet.

关于Java Applet的内容还是不少,这里只是记录一个简单示例:

HelloWorldApplet.java

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {
   public void paint (Graphics g) {
      g.drawString ("Hello World", 25, 50);
   }
}

demo-applet.html

<html>
   <title>The Hello, World Applet</title>
   <hr>
   <applet code = "HelloWorldApplet.class" width = "320" height = "120">
      If your browser was Java-enabled, a "Hello, World"
      message would appear here.
   </applet>
   <hr>
</html>

上面两个文件放在同个目录下即可。

由于本地机器有安装了JDK8,并且使用的浏览器似乎都不支持Applet,没去深入研究,在命令行进入包含上面两个文件目录,使用JDK8编译HelloWorldApplet.java,执行appletviewer.exe demo-applet.html 正常运行会弹出小程序查看器窗口运行HelloWorldApplet。

一些注意事项:

  • 如果当前JDK不包含appletviewer,在命令行需要指定其他JDK中appletviewer的完整路径,并且java文件需要使用同版本JDK编译
  • appletviewer 后面url参数内容需要是包含<applet>标签的文件;将上面示例demo-applet.html中<applet>…</applet>部分单独取出放到demo.txt文件中,appletviewer.exe demo.txt 这样执行也可以。

另外有看到有不少文章说 “应用程序的主类不一定要求是 public 类,但小程序的主类要求必须是 public 类。”,我找了下没找到出处,将HelloWorldApplet类定义中的public去掉,编译后运行appletviewer查看时,提示错误如下:

加载: HelloWorldApplet.class不是公共的, 或者没有公共构造器。
java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class HelloWorldApplet with modifiers “”
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.Class.newInstance(Class.java:436)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:799)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:728)
at sun.applet.AppletPanel.run(AppletPanel.java:378)
at java.lang.Thread.run(Thread.java:748)

当HelloWorldApplet类定义不指定public时,只有同包可以访问,当通过sun.applet.AppletPanel的run方法访问该类就出错了。

Comments are closed