问题
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);
}
回答1:
You may be confounding class hierarchy with containment hierarchy. The declaration JFrame extends Window represents a subclass / superclass relationship, while getWindowAncestor() examines the relationship of two Container instances. Note that JFrame is a top-level container and a subclass of Window.
来源:https://stackoverflow.com/questions/14335963/swingutilities-windowforcomponentjframe-returns-null