frame
是我的 Swing 应用程序中唯一的 JFrame
。由于 JFrame
扩展了 Window
,我从描述和方法名称中相信代码应该返回框架本身。
SwingUtilities.windowForComponent(frame)
public static Window windowForComponent(Component aComponent)
Return aComponent's window
但是它返回null
,因为实现是这样的
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;
}
您是否同意方法实现不精确?
UPD:我的意思是 JFrame 被传递给方法 windowForComponent
,JFrame
extends Window
所以应该有像这样进行额外检查
if (c instanceof Window) return (Window)c; //in windowForComponent
UPD2:所以我必须实现
public static Window windowForComponent (Component c) {
if (c instanceof Window)
return (Window)c;
return SwingUtilities.windowForComponent(c);
}
最佳答案
您可能会混淆class 层次结构和containment 层次结构。声明 JFrame extends Window
表示子类/父类(super class)关系,而 getWindowAncestor()
检查两个 Container
实例的关系。请注意,JFrame
是一个 top-level container
和 Window
的子类。
关于java - SwingUtilities.windowForComponent(JFrame) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335963/