Using Components, the GUI Building Blocks |
Container events are generated by aContainer
just after a component is added to or removed from the container. These events are for notification only -- no container listener need be present for components to be successfully added or removed.Container Event Methods
TheContainerListener
interface and its corresponding adapter class,ContainerAdapter
, contain two methods:
void componentAdded(ContainerEvent)
- Called by the AWT just after a component is added to the listened-to container.
void componentRemoved(ContainerEvent)
- Called by the AWT just after a component is removed from the listened-to container.
Examples of Handling Container Events
The following applet demonstrates container events. By clicking "Add a button" or "Remove a button", you can add components to or remove them from a panel at the bottom of the applet. Each time a component is added to or removed from the panel, the panel fires off a container event, and the panel's container listener is notified. The listener displays descriptive messages in the text area at the top of the applet.
Note: The above applet requires JDK 1.1. If you are using an older browser that does not support 1.1, you won't be able to run the applet. Instead, you need to view this page in a 1.1 browser, such as HotJava, the JDK Applet Viewer (appletviewer
), or certain versions of Netscape Navigator and Internet Explorer. For more information about running applets, refer to About Our Examples.
Try this:
- Click the button labeled "Add a button".
You'll see a button appear near the bottom of the applet. The container listener (in this example, an instance ofContainerEventDemo
) reacts to the resulting component-added event by displaying "Button #1 was added to java.awt.Panel" at the top of the applet.- Click the button labeled "Remove a button".
This removes the most recently added button from the panel, causing the container listener to receive a component-removed event.
You can find the applet's code in ContainerEventDemo.java. Here is the applet's container event handling code:
public class ContainerEventDemo ... implements ContainerListener ... { ...//where initialization occurs: buttonPanel = new Panel(); buttonPanel.addContainerListener(this); ... public void componentAdded(ContainerEvent e) { displayMessage(" added to ", e); } public void componentRemoved(ContainerEvent e) { displayMessage(" removed from ", e); } void displayMessage(String action, ContainerEvent e) { display.append(((Button)e.getChild()).getLabel() + " was" + action + e.getContainer().getClass().getName() + "\n"); } ... }
The
ContainerEvent
ClassEach container event method has a single parameter: aContainerEvent
object. TheContainerEvent
class defines two useful methods:
Component getChild()
- Returns the component whose addition or removal triggered this event.
Container getContainer()
- Returns the container that fired this event.
Using Components, the GUI Building Blocks |