The Applet Code

	import java.awt.*;
	import java.applet.Applet;

	public class HelloWorld extends Applet {
    	  	public void paint(Graphics g) {
        		g.drawString("Hello world!", 25, 25);
    		}
	}
This applet code when executed by the web browser will print "Hello world!" to the screen, at coordinates (25,25).

Consider the first two lines in the HelloWorld applet :

	import java.awt.*;
	import java.applet.Applet;
Java programs usually begin with one or more import statements. The import statement tells the Java compiler that the program will use one or more of the classes in the java.awt package, e.g. the Graphics class (java.awt.Graphics), and that the program will use the Applet class from the java.applet package. Think of an import statment as similar to #include statments in C or C++. Just as the #include statements tell the C/C++ compiler the names of the files that contain class and constant definitions, the import statement tells the Java compiler the names of files that contain your applet's class libraries.

Every Java applet you create must define an Applet class. The Applet class definition specifies the class name. For example, to define its Applet class, the HelloWorld applet uses the following statement:

	public class HelloWorld extends Applet 
The statement defines HelloWorld as the Applet class name. The public keyword tells the Java compiler that objects outside the current file can use the HelloWorld class. All public classes must reside in their own source file, which has the same name as the class and uses the .java extension.

The extends keyword tells the Java compiler that the HelloWorld class extends an existing class (inheritance!). The HelloWorld class inherits the Applet class data and methods.

The next line of the HelloWorld applet is:

	public void paint (Graphics g) { 
Each time an applet must redraw its applet window contents, the Applet class calls the paint method. By redefining the paint method, the applet can control what items it redraws within the applet window. The HelloWorld applet, redefines the paint method to display its text message. The paint method takes a single argument, the Graphics object g. The Graphics object is the graphics context and contains attributes such as the current window color, font, font size, etc.

The final line is:

	g.drawString ("Hello World!", 25, 25);
Here, you are informing the Graphics object g, to draw the string "Hello World!" onto the screen, at the (x,y) position on your screen, where the origin of the coordinate system is at the top left corner of the screen. The x- and y-coordinates are given in pixels.


Back to Lecture2