java - SwingUtilities.windowForComponent(JFrame) 返回 null

标签 java swing jframe swingutilities

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 被传递给方法 windowForComponentJFrame 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 containerWindow 的子类。

关于java - SwingUtilities.windowForComponent(JFrame) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335963/

相关文章:

Java Swing JButton 必须创建 4 个新对象并添加到 JPanel

java - 如何根据组合框选择更改 UI

java - 第二个 JFrame 中的组件未显示

java - JFrame问题

java - volatile、final 和 synchronized 之间安全发布的区别

java - Eclipse MapReduce 错误 : UnModifiableMap

java - 跨表单验证问题 Tapestry

java - 如何在 Java Graphics 中正确渲染颜色

java - 这个类如何在鼠标按下后自动重绘?

java - 当你关闭其他界面时,如何防止主界面关闭?