1.3.1.1 Creating and Running the Echo Applet


By following the steps on this page, you can create and use a Java applet that echoes a given parameter in the Web page twice.
  1. Create a Java Source File
  2. Compile the Java Code
  3. Create an HTML File that Includes the Applet
  4. View the HTML File

Create a Java Source File
Create a file named EchoApplet.java with the Java code shown here:
import java.applet.Applet;
import java.awt.Graphics;

public class EchoApplet extends Applet {
  String s;

  public void init () {
    s = getParameter("text");
    if (s == null) 
      s = "What, no parameter to echo?";
  }

  public void paint(Graphics g) {
    g.drawString(s, 40, 50);
    g.drawString(s, 40, 70);
  }
}

Compile the Java Code
To compile the source file, you type (under Unix or DOS shell) on the command line:
javac EchoApplet.java
If compilation succeeds, the compiler creates a file named EchoApplet.class. This file contains the bytecodes of your applet, i.e. the code that is suitable for the hypothetical system called Java Virtual Machine to run your program on. If compilation fails, make sure you typed in and named the program exactly as shown above.

Create an HTML File that Includes the Applet
Create a file, say EchoApplet.html in the same directory that contains EchoApplet.class. This HTML file should contain the following text:
<HTML>
<HEAD>
<TITLE>The Echo Applet</TITLE>
</HEAD>
<BODY>

<APPLET CODE="EchoApplet.class" WIDTH=200 HEIGHT=100>
<PARAM name="text" value="Hello Ana and Bob">
</APPLET>

</BODY>
</HTML>

View the HTML File
View the HTML file with a Java-enabled Web browser such as Netscape Navigator, Netscape Communicator, Microsoft Internet Explorer, or HotJava from SUN Microsystems, or with the appletviewer that comes along with Java development environment. In the latter case you enter (under Unix or DOS shell) on the command line
appletviewer EchoApplet.html
In a Web browser you should see something like the following