Java JPanel handle container event

Description

Java JPanel handle container event

import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;

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

public class Main {

  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);
      }// ww  w .  ja  v  a2s  .  com

      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);
  }

}



PreviousNext

Related