Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't run java HelloWorld

 
Lydia Zhang
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,
I made my first Applet "HelloWorld.java" and "Hello.html" files into the same folder C:\Java.
When I run from the CP, C:\Java>javac HelloWorld.java---it's OK.
Then I run C:\Java>java HelloWorld
It gave me an error called Exception in thread "main" java.lang.NoSuchMehtodError.main
But if I run C:\Java>appletviewer Hello.html instead, It works.
My HelloWorld.java file code is as following:
import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet{
public void paint(Graphics g){
g.drawString("Hello World!", 50, 25);
}
}
The HTML file is:
<HTML>
<HEAD>
<TITLE>A Simple Program</TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Is there anything wrong?
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wrong, no. Missing, yes.
In order for your code to execute as both an applet and an application, you need to incorporate a main method into your code.
Also, a browser or a program that just runs an applet has to a way to render graphics. A main method doesn't do that automatically; you need to add it.
Consider this:

In this example, I've constructed an object of type HelloWorld in the main method, then created a Frame to put the HelloWorld object in. After giving the frame size and visibility, I call up a graphics context so it can be passed to the applet's paint() method.
What we do in this main() method is a skeletal example of what a browser does and what appletviewer does. Now you can run this program either way.
 
Lydia Zhang
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Michael, it works well now! Also I am reading the book "Complete Java2 Certifucation Study Guide" these days, and plan to take the exam in August. It's a great book, you did a great job. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic