How to Write a Container Listener : ContainerListener « Swing Event « Java Tutorial






Container events are fired after a component is added to or removed from the container.

How to Write a Container Listener
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class UsingContainerListener {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel buttonPanel = new JPanel();
    buttonPanel.addContainerListener(new ContainerListener() {

      public void componentAdded(ContainerEvent e) {
        displayMessage(" added to ", e);
      }

      public void componentRemoved(ContainerEvent e) {
        displayMessage(" removed from ", e);
      }

      void displayMessage(String action, ContainerEvent e) {
        System.out.println(((JButton) e.getChild()).getText() + " was" + action
            + e.getContainer().getClass().getName());
      }
    });
    buttonPanel.add(new JButton("A"));

    frame.add(buttonPanel);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}








15.11.ContainerListener
15.11.1.How to Write a Container ListenerHow to Write a Container Listener
15.11.2.ContainerListener and ContainerEventContainerListener and ContainerEvent
15.11.3.Using ComponentListener to catch the JFrame Maximization event
15.11.4.Determining When a Component Is Added or Removed from a Container