Importing Classes and Packages for Applets

Started by sukishan, Jul 15, 2009, 03:04 PM

Previous topic - Next topic

sukishan

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 for information on using the package statement.
A good beginning makes a good ending

Quick Reply

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Note: this post will not display until it has been approved by a moderator.

Name:
Email:
Verification:
Please leave this box empty:
Type the letters shown in the picture
Listen to the letters / Request another image

Type the letters shown in the picture:

Shortcuts: ALT+S post or ALT+P preview