Swing Containers : Top-Level Containers

There are two types of top-level containers in Swing: applets and windows. An applet in Swing is a subclass of JApplet, as indicated by the declaration

public class Multiply extends JApplet

An applet will have an associated layout. An applet will contain components or other intermediate-level containers such as panels. An applet is downloaded by a Java-enabled Web browser then run.

The second type of top-level container is a window. If we wish to add a GUI to a Java application, then we must use a window container. More precisely, we would use a subclass of a window, namely, a frame. A frame consists of a window together with a title bar.

public class CustomerDetails extends JFrame .....

The javax.swing.JFrame class provides a number of methods: setTitle, setSize, and setVisible are among the most useful. setTitle is used to set the text in the title bar. setSize is used to set the size of the frame in pixels. The contents of a frame need to be made explicitly visible using the setVisible(true) method. A frame will have an associated layout. A frame will contain components or other intermediate-level containers such as panels.

Swing components can be added to panels, but panels and components cannot be directly added to top-level applet or frame containers. Top-level containers consist of an intermediate container, the content pane. The content pane contains all the visible components in the window's GUI. Components that would otherwise be added to the top- level container are added to the content pane. The methods javax.swing.JFrame.getContentPane and javax.swing.JApplet.getContentPane
return the content pane for the current frame or applet, respectively. The content pane is actually an AWT (not Swing) object of type java.awt.Container, so to abbreviate class names a program should include the statement

import java.awt.Container;

The following is a code fragment for getting the content pane, cp, for the current applet or frame, and adding a button component, button1, to the content pane:

Container cp;

cp = this.getContentPane();
cp.add(button1);

No comments:

Post a Comment