Demonstrating the ContainerListener : Various Event Listener « Swing JFC « Java






Demonstrating the ContainerListener

Demonstrating the ContainerListener
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;

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

public class ContainerTest {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    Container contentPane = frame.getContentPane();

    ContainerListener cont = new ContainerListener() {
      ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          System.out.println("Selected: " + e.getActionCommand());
        }
      };

      public void componentAdded(ContainerEvent e) {
        Component c = e.getChild();
        if (c instanceof JButton) {
          JButton b = (JButton) c;
          b.addActionListener(listener);
        }
      }

      public void componentRemoved(ContainerEvent e) {
        Component c = e.getChild();
        if (c instanceof JButton) {
          JButton b = (JButton) c;
          b.removeActionListener(listener);
        }
      }
    };

    contentPane.addContainerListener(cont);

    contentPane.setLayout(new GridLayout(3, 2));
    contentPane.add(new JButton("First"));
    contentPane.add(new JButton("Second"));
    contentPane.add(new JButton("Third"));
    contentPane.add(new JButton("Fourth"));
    contentPane.add(new JButton("Fifth"));

    frame.setSize(300, 200);
    frame.show();
  }
}


           
       








Related examples in the same category

1.Demonstrating the WindowListener with a WindowAdapterDemonstrating the WindowListener with a WindowAdapter
2.Demonstrating the ActionListenerDemonstrating the ActionListener
3.Demonstrating the AdjustmentListenerDemonstrating the AdjustmentListener
4.Demonstrating the AncestorListener
5.Demonstrating the ComponentListenerDemonstrating the ComponentListener
6.Demonstrating the FocusListenerDemonstrating the FocusListener
7.Demonstrating the HyperlinkListenerDemonstrating the HyperlinkListener
8.Demonstrating the InternalFrameListenerDemonstrating the InternalFrameListener
9.Demonstrating the ItemListenerDemonstrating the ItemListener
10.Demonstrating the KeyListenerDemonstrating the KeyListener
11.Demonstrating the MenuListenerDemonstrating the MenuListener
12.Demonstrating the MouseListener and MouseMotionListenerDemonstrating the MouseListener and MouseMotionListener
13.Demonstrating the MouseWheelListenerDemonstrating the MouseWheelListener
14.Demonstrating the PopupMenuListenerDemonstrating the PopupMenuListener
15.Demonstrating the WindowListener
16.Responding to KeystrokesResponding to Keystrokes