CS290W - Compiling and running your first Java applet

This document was written by CS 290W TA Joshua Kay and was last modified .

Okay, we are going to write and compile an Applet real quick here. We will open a text editor, and type in the following:

import java.applet.*; import java.awt.*; public class Hello extends Applet { public void paint(Graphics g) { g.drawString("Hello, CS290w", 5,25); } }

Now we will save this as Hello.java. Your file name HAS to match your class name and case matters.

Now type in the following:

<HTML> <HEAD><TITLE>Hello Applet</TITLE></HEAD> <BODY> <H1>Hello Applet</H1> Below is my first Java applet and I am really excited about it.... <P> <APPLET CODE="Hello" WIDTH=200 HEIGHT=200> </APPLET> <P> How do you like it? <P> </BODY> </HTML>

Save this as Hello.html, in the same directory as your Hello.java file. The html file does not NEED to be named the same as the Java file, but it's not a bad idea - it will keep you organized.

Now we're going to compile the Hello.java using the JDK javac tool. This stands for java compiler.

We will type in javac Hello.java, and provided we don't have any errors, this will generate a file called Hello.class - which will be the executable bytecode for the java source code. Of course, Hello.html must be world-readable. But, so must Hello.class. Notice that Hello.class does NOT need to be world-executable, because it will be sent from the server to the browser which will do the "executing".

Now take a look at the Hello.html file in a Web browser to see what your applet does!

Special note: You will most likely want to keep your java and class files in a sub-directory of www (maybe called "java" with your Hello.html file back in www. In that case you must use the CODEBASE attribute in the APPLET tag as shown below. Obviously, the example above shows that without this tag, the applet must be in the same directory as the HTML file:

<HTML> <HEAD><TITLE>Hello Applet</TITLE></HEAD> <BODY> <H1>Hello Applet</H1> Below is my first Java applet and I am really excited about it.... <P> <APPLET CODEBASE="java" CODE="Hello" WIDTH=200 HEIGHT=200> </APPLET> <P> How do you like it? <P> </BODY> </HTML>

What you put inside the APPLET container will be displayed by Web browsers that do not understand the APPLET tag:

<APPLET CODE="Globe" WIDTH=350 HEIGHT=425> It is a pity that you cannot see the rotating, clickable globe, but alas, your Web browser does not support Java applets :-( </APPLET>

Other attributes, besides CODE, WIDTH, HEIGHT, and CODEBASE, that can be used with the APPLET tag include ALIGN (TOP, MIDDLE, BOTTOM, LEFT, RIGHT), NAME, HSPACE, and VSPACE.