Java examples for Swing:JComponent
Adds a listener to the window parent of the given component.
//package com.java2s; import java.awt.Component; import java.awt.Window; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.WindowListener; import javax.swing.SwingUtilities; public class Main { /**/* w ww . j a va2 s. co m*/ * Adds a listener to the window parent of the given component. Can be * called before the component is added to its hierachy. */ public static void addWindowListener(final Component source, final WindowListener listener) { if (source instanceof Window) { ((Window) source).addWindowListener(listener); } else { source.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == HierarchyEvent.SHOWING_CHANGED) { SwingUtilities.getWindowAncestor(source) .addWindowListener(listener); } } }); } } }