我正在尝试使用 IntelliJ 设置一个简单的 JApplet
。我有一个名为 Square
的类和一个应该可以使其工作的 HTML 文件,但我不断收到 ClassNotFoundException
。
import javax.swing.*;
import java.awt.*;
public class Square extends JApplet {
int size = 40;
public void init() {
JButton butSmall = new JButton("Small");
JButton butMedium = new JButton("Medium");
JButton butLarge = new JButton("Large");
JButton butMessage = new JButton("Say Hi!");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
}
class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(20, 20, theApplet.size, theApplet.size);
}
}
和 HTML 文件
<HTML>
<APPLET CODE="Square.class"> WIDTH=400 HEIGHT=200>
</APPLET>
</HTML>
这是文件夹结构。我尝试了很多不同的组合、名称和 <> 分隔符,但无法正确打开它。
最佳答案
问题是小程序容器(通常是浏览器)已被告知在哪里可以找到类 Square
但不是类 SquarePanel
。您可以执行以下两种操作之一:
将您的类封装在 JAR 中并指定
archive
您的名字<APPLET\>
标签,如图here .巢
SquarePanel
在Square
,如下所示以供说明。
JAR 是首选方法,但也可以考虑 hybrid以实现更灵活的测试和部署。为了方便appletviewer
测试,该标签包含在注释中,如图here .
命令行:
$ appletviewer Square.java
代码,经测试:
// <applet code='Square' width='400' height='200'></applet>
import javax.swing.*;
import java.awt.*;
public class Square extends JApplet {
int size = 40;
public void init() {
JButton butSmall = new JButton("Small");
JButton butMedium = new JButton("Medium");
JButton butLarge = new JButton("Large");
JButton butMessage = new JButton("Say Hi!");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private static class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(20, 20, theApplet.size, theApplet.size);
}
}
}
关于java - 调用Applet时出现ClassNotFound异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26676803/