The procedure to create and run an applet goes as follows for
an applet that simply displays "Hello
World!" in its graphical window and also prints it
to the Java console:
Step 1: Use an editor to enter the following code for
HelloWorld
applet:
HelloWorld Applet |
public
class HelloWorld extends java.applet.Applet
{
public
void paint(java.awt.Graphics g)
{
g.drawString("Hello
World!",50,25);
System.out.println("Hello
World!");
}
}
|
Save this code into a file called HelloWorld.java .
(Note that the name of the file, including the case of each letter,
must match exactly with the class name HelloWorld.)
Step 2: Then compile the application with*
This creates the class file
Step 3: Next you must create a web page file to hold the
applet. (If you are unfamiliar with hypertext and web pages, see
the Creating
Web Pages for Applets in the Chapter
1: Supplements section for a brief introduction.)
Put the following code into a hypertext file such as the following
file we could call HelloWorld.html:
HelloWorld.html |
<HTML>
<Head>
<Title> A Simple Program </Title>
<Body>
<Applet
Code="HelloWorld.class" width="150"
height="50">
</Applet>
</Body>
</HTML>
|
and then put this file into the SAME directory
as the HelloWorld.class file. (We will discuss later
how to organize applet files into different directories.)
Step 4: We have included the applet in this web page.
So opening the file HelloWorld.html in your browser will
display the same as the window here.
HelloWorld.java
You can also see the "Hello World!"
line in the Java Console of the browser.
An alternative way to run the applet is with appletviewer:
>
appletviewer HelloWorld.html
We will discuss in later chapters the structure
of Java programs, the class
keyword, etc.
Tips:
Finding the Java Console in the Browser
Most browsers send error messages and print
outputs for applets to a Java Console window. Different
browsers have different ways of opening this window.
- With the new Java
plug-in, the console can be activiated via the "coffee
cup" icon that will appear in the right side of the
Windows start toolbar after the plug-in begins to run.
Just right click on it and a menu will appear from which
you can pick the "Open Console" item. (You can also
go to the "Advanced" tab in the Java control dialog
and select the "Show console" item so that the console
always appears whenever the plug-in runs.)
- In the older Mozilla browser, choose Tools-> Web
Developoment -> Java Console
-
In Netscape, choose the "tools"
in the top menu, "Web Development", and
then "Java Console".
-
In Internet Explorer you must first
enable the console by choosing "Tools" menu,
then "Internet Options" and then in the
"Advanced" page, check "Java console
enabled". Under the "View" menu you
can then open the "Java console". Also,
the output is sent to the c:\Windows\Java\javalog.txt
file.
|
* On the Java
Tools page, see the note
on the javac
-target option.
Latest update: Feb. 12, 2005
|