0

グリッドのようなレイアウトで GUI に配置するボタンのリストを維持したいと考えています。

私は javax.swing.JButton を使用しており、ColoredButton という独自のサブクラスを作成しました。

それらすべてに対して同じ機能を実行できるように、それらを静的な配列リストに保存したい(色を設定する)。これはさほど難しくありませんでした。

現在、初期化時に 3 つの異なるタイプ (コーナー、エッジ、センター ボタン) に分ける機能を追加しようとしています。問題は、これら 3 つの型のいずれかを構築するときはいつでも、それを ColoredButton 静的配列リストとその特定のサブタイプの静的配列リストに追加したいということです。

「this」をパラメーターとして使用して現在の項目をリストに追加しても機能しないことがわかりました (「this」が不完全であるため、null ポインターが返されます)。

その代わりに、私はファクトリ スタイルの構築を使用しています。これが私のスーパークラス ColoredButton とその派生クラスの 1 つです。

public class ColoredButton extends JButton{
    private static ArrayList <ColoredButton> all;

    protected static void addToColored(ColoredButton B){
        all.add(B);
    }

    public static ColoredButton newColoredButton(){
        ColoredButton B = new ColoredButton();
        ColoredButton.all.add(B);
        return B;
    }

    public static void setAll(Color C){
        for(ColoredButton B: ColoredButton.all)
            B.setBackground(C);
    }
}

public class EdgeButton extends ColoredButton {
    private static ArrayList <EdgeButton> all;

    public static EdgeButton newEdgeButton(){
        EdgeButton B = new EdgeButton();
        EdgeButton.all.add(B);
        addToColored(B);
        return B;
    }

    public static void setAll(Color C){
        for(EdgeButton B: EdgeButton.all)
            B.setBackground(C);
    }
}

今、私がこのようなことをしようとすると:

EdgeButton B1 = EdgeButton.newEdgeButton();

NullPointerException が発生します。コンパイラは、エラーが次の行で発生したことを示しています。

EdgeButton.all.add(B);

それで、どこが間違っているのですか?null ptr 例外が発生するのはなぜですか?

前もって感謝します!

4

1 に答える 1