Search code examples
javaswingjframeswingutilities

SwingUtilities.windowForComponent(JFrame) returns null


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);
}

Solution

  • 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.