Creating Java Applets using Kawa

Applets are designed to be included into HTML pages and run either by a web browser such as Netscape or Internet Explorer, or by Applet Viewer, a program that Sun supplies with Java. In either case, you have to create an HTML document. Since applets use graphics and are run in windows, they use java.awt. The letters awt stand for the abstract windowing toolkit.

Create a new file as you did for an application, but this time type an applet. Notice that it extends Applet and that it does not have a main method. The paint method is used in this case to paint a picture on the screen.

// An applet with classes that draw shapes.

import java.awt.*;
import java.applet.Applet;

public class Shapes extends Applet
{
    private RectangularFigure rectangle = new RectangularFigure ();
    private OvalFigure oval = new OvalFigure ();

    public void paint (Graphics g)
    {
        setBackground (Color.cyan);
        rectangle.displayRectangle (g);
        oval.displayOval (g);
    } // method paint
} // class Shapes

// A class that can display a rectangle.
class RectangularFigure
{
    public void displayRectangle (Graphics g)
    {
        g.setColor (Color.blue);
        g.drawRect (10, 15, 125, 85);
    } // method displayRectangle
} // class RectangularFigure

// A class that can display an oval.
class OvalFigure
{
    public void displayOval (Graphics g)
    {
        g.setColor (Color.red);
        g.fillOval (150, 85, 100, 100);
    } // method displayOval
} // class OvalFigure

In Kawa, your applet should look as follows:

Compile your applet and correct any errors that the compiler finds. The resulting class file can be linked into an HTML document using the <applet> tag. Create a new file with the following example file for this applet.

<HTML>
    <HEAD>
        <TITLE>Shapes Example</TITLE>
    </HEAD>
    <BODY>
        <H3>Shapes Example</H3>
        <APPLET CODE = "Shapes.class" WIDTH=300 HEIGHT=300></APPLET>
    </BODY>
</HTML>

Save the file on your disk as Shapes.html.
 

You can open it in a browser or view it using Applet Viewer. To launch Applet Viewer, click on the same icon that you used to run an application. For this applet, you should see the picture below.