Java tutorial
//package com.java2s; // The MIT License (MIT) import java.awt.Component; import java.awt.Container; import java.util.Optional; import java.util.function.Predicate; import javax.swing.JPopupMenu; public class Main { /** * Find an ancestor of a component. * @param component the starting component * @param type the required type of the ancestor * @return the first ancestor of the specified type */ public static <T> T findAncestor(Component component, Class<T> type) { return findAncestor(component, type, null); } /** * Find an ancestor of a component. * @param component the starting component * @param type the required type of the ancestor * @param defaultValue the value to use of no ancestor is found * @return the first ancestor of the specified type or {@code defaultValue} */ public static <T> T findAncestor(Component component, Class<T> type, T defaultValue) { return findAncestor(component, type::isInstance).map(type::cast).orElse(defaultValue); } /** * Find an ancestor of a component that matches a condition. * @param component the starting component * @param condition the condition to match * @return the first ancestor for which {@code condition} is true */ public static Optional<Component> findAncestor(Component component, Predicate<Component> condition) { while (component != null && !condition.test(component)) { component = getParent(component); } return Optional.ofNullable(component); } /** * Return the parent of a component. If the component is a popup menu and its parent is null then return its invoker. */ public static Component getParent(Component component) { Container parent = component.getParent(); if (parent == null && component instanceof JPopupMenu) { return ((JPopupMenu) component).getInvoker(); } return parent; } }