Java 如何确定两个组件是否位于同一机架上?(摇摆)

Java 如何确定两个组件是否位于同一机架上?(摇摆),java,swing,jframe,jcomponent,Java,Swing,Jframe,Jcomponent,我可以继续使用getParent()遍历它们的父对象,直到找到共享父对象或null,但这看起来是个糟糕的解决方案,有更好的方法吗 基本上,我的用例是在FocusListener中,在focusLost()上,我想知道我是否对框架之外的内容失去了焦点…JComponent有一个方法 /** * Returns the top-level ancestor of this component (either the * containing <code>Window</code

我可以继续使用getParent()遍历它们的父对象,直到找到共享父对象或null,但这看起来是个糟糕的解决方案,有更好的方法吗

基本上,我的用例是在FocusListener中,在focusLost()上,我想知道我是否对框架之外的内容失去了焦点…

JComponent有一个方法

/**
 * Returns the top-level ancestor of this component (either the
 * containing <code>Window</code> or <code>Applet</code>),
 * or <code>null</code> if this component has not
 * been added to any container.
 *
 * @return the top-level <code>Container</code> that this component is in,
 *          or <code>null</code> if not in any container
 */
public Container getTopLevelAncestor()

因此,您可以比较两个组件的容器

您可以比较以下结果:

SwingUtilities.windowForComponent(comp1).equals(SwingUtilities.windowForComponent(comp2))

SwingUtilities.getWindowAncestor(comp1).equals(SwingUtilities.getWindowAncestor(comp2))
SwingUtilities.getRoot(comp1).equals(SwingUtilities.getRoot(comp2))

SwingUtilities.getWindowAncestor(comp1).equals(SwingUtilities.getWindowAncestor(comp2))
SwingUtilities.getRoot(comp1).equals(SwingUtilities.getRoot(comp2))

为什么要迭代?你不能比较两个组件的父组件吗?它们可以嵌套在几个级别上吗?如果不是,您可以使用
getParent()
,但它们位于不同的级别上,我认为StanislavL的答案应该是这样的。