The previous pages discussed how to draw on the applet's panel
component. However, usually panels are intended to hold user interface
components that provide controls and information for a programs
user.
These components include buttons, labels, textfields, menus, and
several others come with the AWT packages. A Canvas
component provides an area where the program can do drawing tasks
such as displaying a histogram.
Note: The fundamental difference
in the AWT and the Swing approach is that the AWT components are
built with the operating system's GUI components (so-called peer
components) whereas Swing draws its components. (Heavyweight
vs Lightweight components). See Chapter
6: JFC Swing vs AWT.
The following simple applet shows how instances of three kinds
of components - Label,
TextField
and Button
- are added to the applet's panel. The Panel
component is a container subclass so it can hold other components
(Recall that the Applet
class is a subclass of Panel.)
|
import
java.applet.*;
import java.awt.*;
public class CompsApplet extends
Applet
{
public void
init () {
add (new Label
(" A Label"));
add (new TextField
(" A TextField", 10));
add (new Button("A
Button"));
setBackground (Color.blue);
}
} // class CompsApplet
|
How the components are arranged within the panel
is determined by a LayoutManager
class. The FlowLayout
is the default. If you alter the size of the applet (via the tag
attributes), you will see that the arrangement will vary as well,
though the order of the components will follow the order in which
they were added to the panel. In Chapter
7: Java : LayoutManagers we will discuss these classes in
detail.
We will also discuss in Chapter
7: Java how a click on a button initates an event process
that allows a program to respond to user action.
Latest update: Oct. 27, 2004
|