How to determine if 2 components are in one frame? (TURN)

I could go ahead and iterate over my parents using getParent () for each, until I get a common parent or null, but this seems like a bad decision, is there a better approach?

Typically, my use case is in FocusListener, on focusLost () I want to know if I am losing focus on something that is outside of my frame ...

+5
source share
2 answers

You can compare the result:

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

OR

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

OR

 SwingUtilities.getRoot(comp1).equals(SwingUtilities.getRoot(comp2)) 
+3
source

JComponent has a 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

+3
source

Source: https://habr.com/ru/post/1200591/


All Articles