private static AncestorListener createAncestorListener(
			JComponent component, final WindowFocusListener 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
				// TODO AncestorListener.
				final Window window = weakReference.get() == null ? null
						: SwingUtilities.getWindowAncestor(weakReference.get());
				if (window != null) {
					window.removeWindowFocusListener(windowListener);
					window.addWindowFocusListener(windowListener);
					// notify the listener of the original focus state of the
					// window, which ensures
					// that the listener is in sync with the actual window
					// state.
					fireInitialFocusEvent(windowListener, window);
				}
			}

			private void fireInitialFocusEvent(
					WindowFocusListener windowListener, Window window) {
				Window focusedWindow = FocusManager.getCurrentManager()
						.getFocusedWindow();
				// fire a fake event to the given listener indicating the actual
				// focus state of the
				// given window.
				if (window == focusedWindow) {
					windowListener.windowGainedFocus(new WindowEvent(window,
							WindowEvent.WINDOW_GAINED_FOCUS));
				} else {
					windowListener.windowGainedFocus(new WindowEvent(window,
							WindowEvent.WINDOW_LOST_FOCUS));
				}
			}

			public void ancestorRemoved(AncestorEvent event) {
				Window window = weakReference.get() == null ? null
						: SwingUtilities.getWindowAncestor(weakReference.get());
				if (window != null) {
					window.removeWindowFocusListener(windowListener);
				}
			}

			public void ancestorMoved(AncestorEvent event) {
				// no implementation.
			}
		};
	}