SwingUtilities.windowForComponent(JFrame) returns null

倖福魔咒の 提交于 2019-12-23 18:02:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!