The Hello world applet program goes as follows:
The code is written a little bit to the right.
import java.applet.*;When you use classes from other packages than the java.lang package you have to import them, so java can recognise them. Here we import the entire java.applet package and the Graphics class from the java.awt package.
import java.awt.Graphics;
//All applets must be declared publicAs the first comment says, this class must be declared public (one line comments start with // and will not affect the program), this goes for all applets so you will just have to live with it. Since the class is declared public, the file in which you save the code must be called HelloWorld.java. (class_name.java) Remember that java is case sensitive, so you must use capital H and W.
public class HelloWorld extends Applet{//Declare an object of the class String
String text;
public void init(){This is a method which don't return anything (don't worry about return now we'll take that later). You don't have to include this method, but when you start to make bigger programs it would look better, and you will know wher the initializations are.text="Hello World";
}
public void paint(Graphics g){This method paints the graphic onto the applet, it takes one argument (An object of the class Graphics, this is why we imported it in the beginning). to call this method you will have to have an object of this class which you can send to the method, but don't worry about, it is the browsers problem. The fact that this method need an object of the type Graphics, gives us the oportunity to use this objec. Here we use the method drawString from the class Graphics, this method looks something like this:
g.drawString(text,20,20);}
}
Now the program is finnished, you must write it in an ordinary ascii
text editor (ie. notepad in win 95) and save it as HelloWorld.java. Then
open a shell window (ie. msdos prompt), change to the directory in which
you saved the program (with the cd command) and write "javac HelloWorld.java"
to compile it.
Now you will need a html file (I call it HelloWorld.html, but the name
is not important) to view the applet, this file must at leas contain the
following tags:
Now use you favorite browser to view the applet, or the appletviewer
from Sun. If you use the appletviewer the command is:
appletviewer HelloWorld.html
You can view the example here