I have a problem with java applet and graphics. I'm trying to run it in Eclipse and it fails. Im new in java and i hope you can help me. I have two files: Say.java and SayWhat.java. Say.java:
public class Say {
SayWhat word = new SayWhat("Hello World");
}
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?
The Class
SayWhat
should have a public constructor with no arguments.Check the documentation for java.lang.InstantiationException
There are two possible causes:
1) Both code and object attributes are specified in the tag:
The Sun JRE can access either the code or the object attribute, but not both.
2) A code attribute is specified in the tag, and an object attribute is specified in a tag :
EDIT: Add a default constructor, as below:
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). Your class's sole constructor takes an argument:
so the class can't be instantiated without that argument, so it can't be used as an applet.