我正在使用图片和JButton数组编写一个内存匹配游戏,但是当我尝试比较两个被点击的按钮时,我遇到了一个问题。如何存储索引/获取第二个按钮的索引?按钮数组中的所有按钮都链接到同一个actionListener,但据我所知,e.getSource()只会点击第一个按钮。我真的很感激一些帮助。 (我不想粘贴我的整个代码,因为这很多,所以我只是放入我认为相关的部分):
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类中,我尝试做类似的事情,但最终将其移动到Display类,因为Panel无法访问按钮数组。
//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();
}
}
答案 0 :(得分:1)
您可以为ActionListener类提供私有字段,即使它是一个匿名内部类,其中一个字段可以是对最后一个按钮的引用。按下第二个按钮后将其设置为null,您将始终知道按下按钮是针对第一个还是第二个按钮。
如,
class ButtonListener implements ActionListener {
private JButton lastButtonPressed = null;
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if (lastButtonPressed == null) {
// then this is the first button
lastButtonPressed = source;
} else {
// this is the 2nd button
if (source == lastButtonPressed) {
// the dufus is pushing the same button -- do nothing
return;
} else {
// compare source and lastButtonPressed to see if same images (icons?)
// if not the same, use a Timer to hold both open for a short period of time
// then close both
lastButtonPressed = null;
}
}
}
}