Java Code:
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class AncestorSampler {
  public static void main (String args[]) {
    JFrame f = new JFrame("Ancestor Sampler");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    AncestorListener ancestorListener = new AncestorListener() {
      public void ancestorAdded(AncestorEvent ancestorEvent) {
        System.out.println ("Added");
      }
      public void ancestorMoved(AncestorEvent ancestorEvent) {
        System.out.println ("Moved");
      }
      public void ancestorRemoved(AncestorEvent ancestorEvent) {
        System.out.println ("Removed");
      }
    };
    f.getRootPane().addAncestorListener(ancestorListener);
    f.getRootPane().setVisible(false);
    f.getRootPane().setVisible(true);
    f.setSize (300, 200);
    f.setVisible (true);
  }
}