ピクチャとJButton配列を使ってメモリマッチングゲームをコーディングしていますが、クリックされた2つのボタンを比較しようとすると問題が発生しました。 2番目のボタンのインデックスをどのように保存しますか/ 2番目のボタンのインデックスを取得しますか?ボタン配列のすべてのボタンは同じactionListenerにリンクされていますが、e.getSource()は私が知っている限り最初のボタンをクリックするだけです。私は本当にいくつかの助けに感謝します。 (それはたくさんだので、私は、私の全体のコードを貼り付けたくなかったので、私はちょうど私が関連していると思うの部分に入れている):アクションリスナーで複数のJButtonのソースを取得する方法は?
public DisplayMM(ActionListener e)
{
setLayout(new GridLayout(6, 8, 5, 5));
JButton[] cards = new JButton[48]; //JButton board
for(int x = 0; x < 48; x++) //initial setup of board
{
cards[x] = new JButton();
cards[x].addActionListener(e);
cards[x].setHorizontalAlignment(SwingConstants.CENTER);
cards[x].setPreferredSize(new Dimension(75, 95));
}
private class e implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
for(int i = 0; i < 48; i++)
{
if((e.getSource())==(cards[i]))//1st button that was clicked
{
cards[i].setIcon(new ImageIcon(this.getClass().getResource(country[i])));
currentIndex = i;
}
}
//cards[i].compareIcons(currentIndex, secondIndex);
}
}
はまた、私のPanelクラスでは、私がやることを試み似たようなものでしたが、Panelはボタン配列にアクセスできなかったため、Displayクラスに移動しました。
//Panel
public void actionPerformed(ActionEvent e)
{
/*every 2 button clicks it does something and decreases num of tries*/
noMatchTimer = new Timer(1000, this);
noMatchTimer.setRepeats(false);
JButton source = (JButton)e.getSource();
guess1 = source.getText(); //first button clicked
numGuess++; //keeps track of number of buttons clicked
JButton source2 = (JButton)e.getSource();
guess2 = source2.getText();
numGuess++;
if(numGuess == 1)
display.faceUp(cards, array, Integer.parseInt(e.getSource()));
else
display.compareIcons(guess1, guess2);
if(tries != 12 && count == 24)
{
displayWinner();
}
}
あなたはもっと手の込んだことはできますか?最後に押されたボタンをnullに設定するには? – mk8139
@ mk8139:上の例を参照 –
ありがとう、これはとても役に立ちました! – mk8139