问题描述
frame
是我的Swing应用程序中唯一的JFrame
.由于JFrame
是Window
的扩展,我从描述和方法名称相信代码应该返回框架本身.
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)
返回组件的窗口
但是它返回null
,因为实现是这样的
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::我的意思是将JFrame传递给方法windowForComponent
,JFrame
扩展了Window
,因此应该进行其他检查,例如
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:所以我必须实施
public static Window windowForComponent (Component c) {
if (c instanceof Window)
return (Window)c;
return SwingUtilities.windowForComponent(c);
}
推荐答案
您可能正在将 class 层次结构与 containment 层次结构混淆.声明JFrame extends Window
表示子类/超类关系,而getWindowAncestor()
则检查两个Container
实例的关系.请注意,JFrame
是 top-level container
和一个子类Window
.
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
.
这篇关于SwingUtilities.windowForComponent(JFrame)返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!