0

Javaでスライドパズルを作ろうとしています。今、私は少し問題があります。クリックしたボタンのインデックスを知りたいArrayList.

ArrayList<JButton>ボタンには多数の が含まれています。JButton各ボタンに ActionListener を追加してから、 this に配置しましたArrayList

私は何を間違っていますか?

参照としていくつかのコードを次に示します。

public void actionPerformed(ActionEvent ae)
{
    if (buttons.contains(ae.getSource()) == true)
    {
        int click = buttons.indexOf(ae.getSource()); // <--- What's wrong with this?

        System.out.println(click);  /* I checked the index I got by printing 
                                       it out as a test, and it always gives 
                                       me the Integer '0', even if I clicked 
                                       the 9th Button for example. */
    }
    else
    {
        System.out.println("No click");
    }
}
4

1 に答える 1

0

あなたがやりたいことは、各ボタンにクライアントプロパティを設定することです:

JButton one = new JButton("1");
one.putClientProperty("Which", new Integer(1));

次に、アクション リスナー ユーザーで:

JButton button = ae.getSource();
int value = button.getClientProperty("Which").intValue();

いくつかのキャストとエラーチェックを追加する必要がありますが、それが要点です...

于 2013-04-30T21:45:45.033 に答える