【问题标题】:How to determine if 2 components are on the same frame? (SWING) [duplicate]如何确定 2 个组件是否在同一框架上? (摇摆)[重复]
【发布时间】:2014-10-11 09:48:20
【问题描述】:

我可以继续使用 getParent() 遍历他们的父母,直到我得到一个共享的父母或 null,但这看起来是一个糟糕的解决方案,有没有更好的方法?

基本上我的用例在 FocusListener 中,在 focusLost() 上我想知道我是否失去了对框架之外的东西的关注...

【问题讨论】:

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

标签: java swing jframe jcomponent


【解决方案1】:

您可以比较以下结果:

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

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

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

【讨论】:

    【解决方案2】:

    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()
    

    所以你可以比较两个组件的容器

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 2011-06-26
      • 2012-06-30
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多