< Day Day Up > |
Container events are fired by a Container just after a component is added to or removed from the container. These events are for notification onlyno container listener need be present for components to be successfully added or removed. Figure 3 demonstrates container events. By clicking Add a button or Remove a button , you can add buttons to or remove them from a panel at the bottom of the window. Each time a button is added to or removed from the panel, the panel fires 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 window. Figure 3. The ContainerEventDemo application.
Try This:
You can find the demo's code in ContainerEventDemo.java . Here's the demo's container event-handling code: public class ContainerEventDemo ... implements ContainerListener ... { ...//where initialization occurs: buttonPanel = new JPanel(new GridLayout(1,1)); 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(((JButton)e.getChild()).getText() + " was" + action + e.getContainer().getClass().getName() + newline); } ... } The Container Listener APITable 9 lists the methods in the ContainerListener interface and Table 10 describes the methods in the ContainerEvent class. Also refer to the API documentation for ContainerListener at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/ContainerListener.html. The API documentation for ContainerEvent is online at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/ContainerEvent.html. Table 9. The ContainerListener Interface (The corresponding adapter class is ContainerAdapter . [a] )
Table 10. The ContainerEvent Class
Examples That Use Container ListenersThe following examples use container listeners.
|
< Day Day Up > |