Container
class, like Component
is an abstract
class. It has two direct subclasses:
Panel
, which is only used for grouping components;Window
, which is, as its name says, for creating and handling
windows.Panel
is an Applet
,
but you can define as may panels as you wish.
Java distinguishes two kinds of windows:
Dialog
,Frame
.
import java.applet.Applet; import java.awt.*; public class FrameApplet extends Applet { Button openButton; InfoWindow window; public void init() { openButton = new Button("New Window"); add(openButton); } public boolean action(Event evt, Object arg) { if (evt.target == openButton) { window = new InfoWindow("A Simple Window", "Example of a Window"); window.show(); return true; } else { return false; } } }
InfoWindow
object, which will be an extension of a Frame
, and invoke the
show
method in the following way:
window = new InfoWindow("A Simple Window", "Example of a Window"); window.show();
import java.awt.*; public class InfoWindow extends Frame { Button closeButton; Label text; InfoWindow(String title, String message) { super(title); // create frame with specified title setLayout(new BorderLayout()); // set BorderLayout manager text = new Label(message); // create label with specified text closeButton = new Button("Close Window"); // create close button add("Center", text); // add label to frame add("South", closeButton); // add button to frame pack(); // resize frame to preferred size of its components } public boolean action(Event evt, Object arg) { if (evt.target == closeButton) { dispose(); // remove frame and give up resources of frame return true; } else { return false; } } public boolean handleEvent (Event evt) { if (evt.id == Event.WINDOW_DESTROY) { dispose(); } return super.handleEvent(evt); } }
InfoWindow
class as
a subclass of Frame
. It contains a Button
for closing
the window and a label
for displaying a short message.
When the user clicks on the Close Window button, the window should
close and release the resources that are used for the window.
This is handled in the action
method.
If you want the user to be able to close the window via the tools provided
by your platform, e.g. via the Exit button in Windows 95, you need
to provide a handler for the Window_DESTROY
event.
This is done in the handleEvent
method.
You can go one step further with closing frames. Suppose that you have
a Frame
that is a root window for you application and
that your application should stop when the window is destroyed, then
this you should add the following lines of code to the above
handleEvent
method right after the
invocation of dispose
.
SecurityManager security = System.getSecurityManager(); if (security == null) { System.exit(0); }
The Panel
class is mainly used for holding components.
The most important example of a Panel
is an Applet
.
Components can be laid out within a container in two ways: