Class 24: Applets


A Java Applet Example
This webpage demonstrates a Java applet, i.e. a Java program that runs within a webpage.

There's a fair bit of Java code involved in this example: Ex3MOD, Thing, StartActionListener. The big takeaway is this: The browser renders a simple html file - something like this:
<html>
<head></head>
<body>
  <applet code="Ex3MOD.class" width="500" height="500"></applet>
</body>
</html>
... that includes an embeded Java applet via the applet tag. That specifies that some piece of the browser frame (a 500x500 piece in this case) is given over to the executing Java applet. The browser itself launches an instance of the Java virtual machine to execute the applet.

To be runnable as an applet, the program needs to start with a class that extends the JApplet class, and meets some other restrictions, as we discussed in class.

In class we discussed some key issues, like how Java's compile-to-bytecode-then-interpret-with-JVM architecture allows for this kind of mobile code in terms of both portability and security.

A Simple Example
Here's a simple applet and the accompanying html and java code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Ex0 extends JApplet
{
  JLabel lab1, lab2;
  JTextField tf1;
  public void init()
  {
    setLayout(new FlowLayout());
    lab1 = new JLabel("Type and enter!");
    add(lab1);
    tf1 =  new JTextField(20);
    tf1.addActionListener(new TextInput());
    add(tf1);
    lab2 = new JLabel("       ");
    add(lab2);
  }
  class TextInput implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {      
      lab2.setText(tf1.getText());
    }
  }
}
<html>
<head></head>
<body>
  <applet code="Ex0.class" width="300" height="300"></applet>
</body>
</html>

Notice how we use JApplet instead of JFrame, and public void init() instead of a constructor.


Christopher W Brown
Last modified: Wed Aug 19 11:00:04 EDT 2009