A first applet -- applets/hello
Hello outputs a text that is specified in the program.
Hello is an applet and demonstrates how Java is used in Web documents.
An applet is a Java program with a graphical user interface usually based on the Abstract Window Toolkit
(AWT) so that it can be used in suitable browsers. Essentially, only Sun's hotjava and the test program appletviewer
currently understand the finer points of Java 1.1 applets.
An applet is always implemented as a subclass of Applet
; unlike an application
an applet has no main window. It may, however, create windows.
{applets/hello/Hello.java}
import java.applet.*; // find Applet class
import java.awt.*; // find Graphics class
/** A class with the first Java applet */
public class Hello extends Applet {
/** hook to initialize the applet */
public void init () {
resize(150, 25);
}
/** redraw the Applet */
public void paint (Graphics g) {
g.drawString("Hello, World", 50, 25);
}
}
{}
A class can be qualified as public which makes it visible once a package is imported. A public class must be implemented in a file with the same name as the class (watch out for upper/lower case when compiling under Windows).
An Applet object is created by the browser's runtime support which sends init()
to the Applet so that it can initialize itself. There are other ``mile stones'' in the life of the applet.
paint()
is the method in which a Component displays itself.
Graphics
essentially is a graphics context and is used to paint texts, lines, etc.
An applet is called with an <applet> tag from an HTML file:
{applets/hello/0.html}
<html>
<head>
<title>Hello, World</title>
</head>
<body>
Here is the output:
<p>
<applet code="Hello.class" width=150 height=25>
</applet>
<p>
Here is the <a href="Hello.java">source.</a>
</body>
</html>
{}
Compilation and execution could look as follows:
$ javac Hello.java # compiling a file
$ java sun.applet.AppletViewer 0.html # execution the <applet>
appletviewer
is here called as a class. It is a trivial Web browser that only displays applets. Under Unix/X11 or Windows the following windows appear:
|
|
![]()
A Java enabled browser can show the applet page. The <applet> tag could contain text and pictures for the benefit of browsers that do not recognize the tag.