Java tutorial
//package com.java2s; /** * A collection of small utilities for component management and reflection handling. * <p/> * <hr/> Copyright 2006-2012 Torsten Heup * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ import javax.swing.*; import java.awt.*; public class Main { /** * Returns whether a component is a direct descendant of another one. This method will traverse the component * hierarchy, following the 'parent' relation for normal components and the 'invoker' relation for JPopupMenu * instances. * * @param supposedParent The supposed ancestor component * @param supposedChild The supposed child component * @return if 'supposedChild' is a descendant of 'supposedParent' */ public static boolean isDescendant(final Component supposedParent, final Component supposedChild) { if (supposedParent == null) throw new IllegalArgumentException("Parameter 'supposedParent' must not be null!"); if (supposedChild == null) throw new IllegalArgumentException("Parameter 'supposedChild' must not be null!"); Component runner = supposedChild; while (runner != null) { if (runner == supposedParent) return true; if (runner instanceof JPopupMenu) runner = ((JPopupMenu) runner).getInvoker(); else runner = runner.getParent(); } return false; } /** * Returns the parent for the given component. Other than Component#getParent(), this method will work for popup * menus as well, returning the menu's invoker rather than its own window instance. * * @param c Component to query * @return Parent element of the given component. */ public static synchronized Component getParent(final Component c) { if (c instanceof JPopupMenu) return ((JPopupMenu) c).getInvoker(); else return c.getParent(); } }