load:找不到类MyApplet:java.lang.ClassNotFoundException。当包中有类文件时,为什么我会这样做?

时间:2012-07-09 14:04:30

标签: java html jar applet classnotfoundexception

当我尝试运行applet时出现以下异常:

load: class MyApplet not found.
java.lang.ClassNotFoundException: MyApplet
at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
... 9 more
Exception: java.lang.ClassNotFoundException: MyApplet

小程序代码:

import javax.swing.*;
import java.awt.*;

public class MyApplet extends JApplet {

public JFrame frame;
public JPanel panel;
public JButton button;

public void init() {
    frame = new JFrame();
    panel = new JPanel();
    button = new JButton("click me ");
    panel.setBackground(Color.RED);
    panel.add(button);
    frame.add(panel);
    frame.setSize(300,300);
    frame.setVisible(true);
}   
}

html代码:

<applet code="MyApplet" codebase="AppletPackage" archive="JAR.jar" height="800" width="800">

JAR.jar文件包含一个Applet包,该包包含一个名为MyApplet.class

的类文件

enter image description here

为什么我会得到这个例外? Whare我犯了错误吗?

2 个答案:

答案 0 :(得分:2)

archive参数相对于codebase参数已解析。因此,在您的情况下,插件会查找文件MyApplet.class中包含的文件AppletPackage/JAR.jar

您应该将其更改为以下内容:

<applet code="AppletPackage.MyApplet" archive="JAR.jar" height="800" width="800">

这将在与HTML文件相同的目录中解析为AppletPackage/MyApplet.class内的JAR.jar

答案 1 :(得分:1)

这是尝试解决第一个回答的评论中报告的错误消息:

java.lang.NoClassDefFoundError: AppletPackage/MyApplet (wrong name: MyApplet)

查看the sources,我发现此“错误名称”错误消息表示文件名和类名不匹配。您声称自己的班级位于AppletPackage内,文件名AppletPackage/MyApplet.class符合此类。但是您上面引用的源代码不包含行

package AppletPackage;

您应该添加该行,以便类文件包含该类的完全限定名称。然后你应该能够加载它。