code: private static AncestorListener createAncestorListener(JComponent component, final WindowListener windowListener) {
          final WeakReference<JComponent> weakReference = new WeakReference<JComponent>(component);
  
          return new AncestorListener() {
              public void ancestorAdded(AncestorEvent event) {
                  // TODO if the WeakReference's object is null, remove the
                  // WeakReference as an AncestorListener.
                  Window window = weakReference.get() == null ? null : SwingUtilities.getWindowAncestor(weakReference.get());
  
                  if (window != null) {
                      window.removeWindowListener(windowListener);
                      window.addWindowListener(windowListener);
                  }
              }
  
              public void ancestorRemoved(AncestorEvent event) {
                  Window window = weakReference.get() == null ? null : SwingUtilities.getWindowAncestor(weakReference.get());
  
                  if (window != null) {
                      window.removeWindowListener(windowListener);
                  }
              }
  
              public void ancestorMoved(AncestorEvent event) {
                  // no implementation.
              }
          };
      }
docs: Create the ancestor listener.
  
  @param  component      the component.
  @param  windowListener the listener.
  
  @return the weak referenced listener.