Java 小程序错误

标签 java applet

我刚刚开始学习 Java(哇哦!!),我正在读一本名为《Java 编程简介》的书。

这本书有一些例子,例如如何创建小程序,我一直在尝试自己做,但没有成功,即使在尝试复制他们的示例后,它仍然没有成功'不工作。我编写类并编译它,然后将类复制到与我的 html 文件和状态相同的文件夹中

<applet code="StaticRects.class" height=160 width=300></applet>

代码如下:

package helloworld;

import java.awt.*;

/**
 *
 * @author RikudoSennin
 */
public class StaticRects extends AnimationBase {

    public void drawFrame(Graphics g) {
// Draw set of nested black rectangles on a red background.
// Each nested rectangle is separated by 15 pixels on all sides
// from the rectangle that encloses it. The applet is
// assumed to be 300 pixels wide and 160 pixels high.
        int inset; // Gap between borders of applet and one of the rectangles.
        int rectWidth, rectHeight; // The size of one of the rectangles.
        g.setColor(Color.red);
        g.fillRect(0, 0, 300, 160); // Fill the entire applet with red.
        g.setColor(Color.black); // Draw the rectangles in black.
        inset = 0;
        rectWidth = 299; // Set size of the first rect to size of applet
        rectHeight = 159;
        while (rectWidth >= 0 && rectHeight >= 0) {
            g.drawRect(inset, inset, rectWidth, rectHeight);
            inset += 15; // rects are 15 pixels apart
            rectWidth -= 30; // width decreases by 15 pixels on left and 15 on right
            rectHeight -= 30; // height decreases by 15 pixels on top and 15 on bottom
        }
    } // end paint()
} // end class StaticRects

(这是复制的版本)

现在,我收到以下错误:

java.lang.NoClassDefFoundError: StaticRects (wrong name: helloworld/StaticRects)

请注意,AnimationBase 是在项目中其他位置定义的类,它扩展了JApplet,并且它的类包含在同一目录中。

我做错了什么? (这可能是一些菜鸟错误,但话又说回来,我 Java 菜鸟)。

非常感谢所有的答案,提前致谢:)

编辑:哦,是的,我正在使用 JDK 1.7.0 和 NetBeans 7.0.1。

最佳答案

包名称必须出现在三个位置:

  • 在 Java 源文件中

    package helloworld;

  • 在小程序标签中:

    <applet code="helloworld.StaticRects" height=160 width=300></applet>

  • 作为代码库目录的子目录,默认情况下是包含 HTML 文件的目录:

    blah/mypage.html

    blah/helloworld/StaticRects.class

如果您可以让不同的小程序在指定包中工作,那么问题一定出在代码上。您的StaticRects如果我使用以下最小 AnimationBase ,类对我来说效果很好类:

package helloworld;

import java.awt.Graphics;
import javax.swing.JApplet;

public abstract class AnimationBase extends JApplet {
    public void paint(Graphics g) {
        this.drawFrame(g);
    }

    public abstract void drawFrame(Graphics g);
}

我的目录层次结构如下所示:

html/: applet.html helloworld

html/helloworld: AnimationBase.class StaticRects.class

关于Java 小程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7222179/

相关文章:

Google 协作平台中的 Java 小程序和 "Incompatible Magic Number"错误

java - 无法将类型 [JmsManagedConnectionFactoryImpl] 的值转换为所需类型 [javax.jms.ConnectionFactory]

java - 我怎样才能正确使用<s :action name ="populate" executeResult ="true"/>?

Java:读取 Windows 注册表项停止工作

java - 在Java Applet中绘制图像和ImageObserver

java - 如何让一个简单的 Hello World Java 小程序在 Mac OS X 的浏览器中工作?

java - 从单个类文件生成 Jar 文件

javascript - 为什么我无法读取在 POST 中收到的参数?

java - 如何将字符串存储在数组中,然后打印它的放入顺序

java - 一个事务中的多个聚合实例