Java Swing AncestorListener handle component ancestor event

Description

Java Swing AncestorListener handle component ancestor event

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      AncestorListener ancestorListener = new AncestorListener() {
         public void ancestorAdded(AncestorEvent ancestorEvent) {
            System.out.println("Added");
         }/*from w  w w  .ja  v  a  2s  .c  om*/

         public void ancestorMoved(AncestorEvent ancestorEvent) {
            System.out.println("Moved");
         }

         public void ancestorRemoved(AncestorEvent ancestorEvent) {
            System.out.println("Removed");
         }
      };
      JButton bn = new JButton();
      bn.addAncestorListener(ancestorListener);
      frame.add(bn);
      // frame.remove(bn);
      frame.setSize(300, 200);
      frame.setVisible(true);
   }
}



PreviousNext

Related