TreeWalker { public static boolean isAncestor(@NotNull Container ancestor, @NotNull Component child) { if (child == ancestor) { return true; } else if (child.getParent() == null) { return false; } else { return isAncestor(ancestor, child.getParent()); } } TreeWalker(@NotNull Component root); static boolean isAncestor(@NotNull Container ancestor, @NotNull Component child); Stream<Component> ancestorStream(); Iterable<Component> ancestors(); Stream<Component> descendantStream(DescendantOrder order); Iterable<Component> descendants(DescendantOrder order); Stream<Component> descendantStream(); Iterable<Component> descendants();  }
@Test public void isAncestorWorks() throws Exception { JPanel panel1 = new JPanel(); JPanel panel11 = new JPanel(); JPanel panel12 = new JPanel(); JPanel panel123 = new JPanel(); JPanel panel13 = new JPanel(); panel1.add(panel11); panel1.add(panel12); panel12.add(panel123); panel1.add(panel13); assertThat(TreeWalker.isAncestor(panel1, panel123)).isTrue(); assertThat(TreeWalker.isAncestor(panel123, panel1)).isFalse(); assertThat(TreeWalker.isAncestor(panel1, panel1)).isTrue(); assertThat(TreeWalker.isAncestor(panel11, panel123)).isFalse(); assertThat(TreeWalker.isAncestor(panel12, panel123)).isTrue(); }