3

frameJFrame私のSwingアプリで唯一です。JFrameextends以来Window、説明とメソッド名から、コードはフレーム自体を返す必要があると信じていました。

SwingUtilities.windowForComponent(frame)

public static Window windowForComponent(Component aComponent)

コンポーネントのウィンドウを返す

しかし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拡張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);
}
4

1 に答える 1

2

クラス階層と包含階層を混同している可能性があります。宣言JFrame extends Windowはサブクラス/スーパークラスの関係を表し、 2 つのインスタンスgetWindowAncestor()の関係を調べます。はおよび のサブクラスであることにContainer注意してください。JFrametop-level containerWindow

于 2013-01-15T11:10:31.627 に答える