我刚刚开始学习 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/