Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 337
Nikolay Kuznetsov Avatar asked Jun 29 '26 22:06

Nikolay Kuznetsov


1 Answers

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.

like image 65
trashgod Avatar answered Jul 01 '26 11:07

trashgod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!