Dissection of the “Hello World” Applet
If you refer back to the HelloWorld.java file you can see that the code starts off with two import statements. By importing classes or packages, a class can more easily refer to classes in other packages. For example if you do not want to import the packages then you have to add the highlighted bits shown below to your HelloWorld.java file:
public class HelloWorld extends java.applet.Applet{
public void paint(java.awt.Graphics g){
g.drawString("Hello world!", 50, 25);
}
}
This might not seem much extra to write at the moment, but believe me when your code is more than 500 lines it is going to be so much easier to just import the packages rather than to include the whole path in your code.
Besides importing individual classes, you can also import entire packages. Here's an example:
import java.applet.*;
import java.awt.*;
Note: You might have noticed that the “Hello World” application example from the previous lesson uses the System class without any fix, and yet does not import the System class. The reason is that the System class is part of the java.lang package, and everything in the java.lang package is automatically imported into every Java program.
There is no overhead involved with importing entire packages so there isn’t any real reason not to!
Lets now move onto the class definition. Every applet must define a subclass of the Applet class. In the "Hello World" applet, this subclass is called HelloWorld. Applets inherit a great deal of functionality from the Applet class, ranging from communication with the browser to the ability to sent a graphical user interface (GUI). The extends keyword indicates that HelloWorld is a subclass of the class whose name follows Applet. If the term subclass means nothing to you don’t panic, you'll learn about it soon.
The HelloWorld applet implements just one method, the paint method. Every applet must implement at least one of the following methods: init, start or paint. Unlike Java applications, applets do not need to implement a main method. We will go into the details of init, start and other methods bit later in the course.
Returning to the above code snippet, the Graphics object passed into the paint method resents the applet's onscreen drawing context. The first argument to the Graphics drawString method is the string to draw onscreen. The second and third arguments are the (x,y) position of the lower left corner of the text onscreen. This applet draws the string "Hello world!" starting at location (50,25). The applet's coordinate system starts at (0,0), which is at the upper left corner of the applet's display area.
No comments:
Post a Comment