0

DesignGridLayout Java ライブラリ(こちら)を使用してグリッド レイアウトを作成します。3 列のレイアウトを作成する場合はサンプルで。
このコードを使用して:

layout.row().add(new JButton("Button 1")).add(new JButton("Button 2")).add(new JButton("Button 3"));

または object を返すメソッドを使用する:

layout.row().add(button()).add(button()).add(button());
...
...
public JButton button() {
    return new JButton("Button");
}

問題は、動的に JButton 値を作成する方法です。名前かアイコンか何か?
私はすでにこのような自分のコードを試しています:

for (int i=0; i<4; i++) {
        JButton button = new JButton();
    layout.row().add(button).add(button).add(button);   
}

戻り値: スレッド「AWT-EventQueue-0」での例外 java.lang.IllegalArgumentException: 同じコンポーネントを 2 回追加しないでください

パネルに追加された各コンポーネントの異なる値の私の目的は、異なる画像を取り込むギャラリーを作成し、次のようにループを使用してその画像をロードすることです:

for(int i=0; i<files.length; i++) {
    ...
    ImageIcon imgSource = new ImageIcon(new File(myPath));
    JLabel labelGallery = new JLabel(imgSource);
    ...
}

解決策はありますか?前にありがとう:)

4

2 に答える 2

2

あなたの例では、

layout.row().add(button).add(button).add(button);

同じ JButtonインスタンスを行に繰り返し追加しようとする効果があります。

引用した例では、

layout.row().grid().add(button()).add(button());

補助メソッド、を呼び出して、button()表示されるたびに新しいインスタンスを作成します。

public static JButton button() {
    return new JButton("Button");
}
于 2013-03-23T15:06:49.353 に答える