The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Deployment
Lesson: Applets

Importing Classes and Packages for Applets

The first two lines of the HelloWorld applet import two classes: JApplet and Graphics.

import javax.swing.JApplet;
import java.awt.Graphics;

public class HelloWorld extends JApplet {
    public void paint(Graphics g) {
	g.drawRect(0, 0, 
		   getSize().width - 1,
		   getSize().height - 1);
        g.drawString("Hello world!", 5, 15);
    }
}

If you removed the first two lines, the applet could still compile and run, but only if you changed the rest of the code like this:

public class HelloWorld extends javax.swing.JApplet {
    public void paint(java.awt.Graphics g) {
        g.drawString("Hello world!", 5, 15);
    }
}

As you can see, importing the JApplet and Graphics classes lets the program refer to them later without any prefixes. The javax.swing. and java.awt. prefixes tell the compiler which packages it should search for the JApplet and Graphics classes.

Both the javax.swing and java.awt packages are part of the core Java API always included in the Java environment.

The javax.swing package contains classes for building Java graphical user interfaces (GUIs), including applets.

The java.awt package contains the most frequently used classes in the Abstract Window Toolkit (AWT).

Besides importing individual classes, you can also import entire packages. Here's an example:

import javax.swing.*;
import java.awt.*;

public class HelloWorld extends JApplet {
    public void paint(Graphics g) {
	g.drawRect(0, 0, 
		   getSize().width - 1,
		   getSize().height - 1);
        g.drawString("Hello world!", 5, 15);
    }
}

In the Java language, every class is in a package. If the source code for a class doesn't have a package statement at the top, declaring the package the class is in, then the class is in the default package. Almost all of the example classes in this tutorial are in the default package. See Creating and Using Packages (in the Deployment trail) for information on using the package statement.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.