4

I could go on and iterate over their parents using getParent() on each until i get to a shared parent or null, but this looks like a bad solution, is there a better approach?

Basiclly my use case is in a FocusListener, on focusLost() i want to know if i am losing focus to something thats outside my frame...

Ofek Ron
  • 8,354
  • 13
  • 55
  • 103
  • Why iterate? Can't you compare the parent of your two components? Can they be nested on several levels? – Djon Aug 18 '14 at 13:05
  • If they were not you could use `getParent()`, but they are on different level I think StanislavL's answer should do. – Djon Aug 18 '14 at 13:09

2 Answers2

3

JComponent has method

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

so you can compare the Containers of both components

StanislavL
  • 56,971
  • 9
  • 68
  • 98
2

You can compare the result of:

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

OR

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

OR

SwingUtilities.getRoot(comp1).equals(SwingUtilities.getRoot(comp2))
One Man Crew
  • 9,420
  • 2
  • 42
  • 51