Java JComponent handle 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 .j a va2 s. com 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); } }