本文介绍了SwingUtilities.windowForComponent(JFrame)返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

frame是我的Swing应用程序中唯一的JFrame.由于JFrameWindow的扩展,我从描述和方法名称相信代码应该返回框架本身.

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传递给方法windowForComponentJFrame扩展了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:00