[英]class can't be instantiated
I have a problem with java applet and graphics. 我有java applet和图形的问题。 I'm trying to run it in Eclipse and it fails.
我试图在Eclipse中运行它,它失败了。 Im new in java and i hope you can help me.
我是java的新手,我希望你能帮助我。 I have two files: Say.java and SayWhat.java.
我有两个文件:Say.java和SayWhat.java。 Say.java:
Say.java:
public class Say {
SayWhat word = new SayWhat("Hello World");
}
SayWhat.java: SayWhat.java:
import java.applet.Applet;
import java.awt.Graphics;
@SuppressWarnings("serial")
public class SayWhat extends Applet {
Graphics g;
String what;
public SayWhat(String what) {
this.what=what;
}
public void paint(Graphics g){
g.drawString(what, 20, 20);
}
}
Error that appears is: 出现的错误是:
load: SayWhat.class can't be instantiated.
java.lang.InstantiationException: SayWhat
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Can you please tell me what am i doing wrong? 你能告诉我我做错了什么吗?
An applet needs to have a public no-arg constructor (either by having an explicit public no-arg constructor, or by having no explicit constructors at all; in the latter case, the compiler will supply a public no-arg constructor as a default). applet需要有一个公共的无参数构造函数(通过具有显式的公共no-arg构造函数,或者根本没有显式构造函数;在后一种情况下,编译器将提供一个公共的无参数构造函数作为默认值)。 Your class's sole constructor takes an argument:
你的类的唯一构造函数需要参数:
public SayWhat(String what) {
so the class can't be instantiated without that argument, so it can't be used as an applet. 因此,如果没有该参数,则无法实例化类,因此不能将其用作applet。
Check the documentation for java.lang.InstantiationException 检查java.lang.InstantiationException的文档
There are two possible causes: 有两个可能的原因:
1) Both code and object attributes are specified in the tag: 1)代码和对象属性都在标记中指定:
<APPLET code=MyApplet object=MyApplet.ser width=100 height=100>
</APPLET>
The Sun JRE can access either the code or the object attribute, but not both. Sun JRE可以访问代码或对象属性,但不能同时访问两者。
2) A code attribute is specified in the tag, and an object attribute is specified in a tag : 2)在标记中指定代码属性,并在标记中指定对象属性:
<APPLET code=MyApplet width=100 height=100>
<PARAM name="object" value="someValue">
</APPLET>
public class MyApplet extends java.applet.Applet
{
public void init()
{
String value = getParameter("object");
}
....
}
EDIT : Add a default constructor , as below: 编辑 :添加默认构造函数 ,如下所示:
public SayWhat() {}
类SayWhat
应该有一个没有参数的公共构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.