frame is the only JFrame in my Swing app. Since JFrame extends Window I have believed from description and method name that the code should return the frame itself.
SwingUtilities.windowForComponent(frame)
public static Window windowForComponent(Component aComponent)
Return aComponent’s window
But it returns null, because implementation is like this
public static Window windowForComponent(Component c) {
return getWindowAncestor(c);
}
public static Window getWindowAncestor(Component c) {
for(Container p = c.getParent(); p != null; p = p.getParent()) {
if (p instanceof Window) {
return (Window)p;
}
}
return null;
}
Do you agree that method implementation is not precise?
UPD: I mean that JFrame is passed to the method windowForComponent, JFrame extends Window so there should be additional check like
if (c instanceof Window) return (Window)c; //in windowForComponent
UPD2: So I would have to implement
public static Window windowForComponent (Component c) {
if (c instanceof Window)
return (Window)c;
return SwingUtilities.windowForComponent(c);
}
You may be confounding class hierarchy with containment hierarchy. The declaration
JFrame extends Windowrepresents a subclass / superclass relationship, whilegetWindowAncestor()examines the relationship of twoContainerinstances. Note thatJFrameis atop-level containerand a subclass ofWindow.