gpt4 book ai didi

java - 如何在 Action 监听器中获取多个JButton的来源?

转载 作者:行者123 更新时间:2023-12-01 09:53:19 25 4
gpt4 key购买 nike

我正在使用图片和 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();
}
}

最佳答案

您可以为 ActionListener 类提供私有(private)字段,即使它是匿名内部类,并且这些字段之一可以是对最后按下的按钮的引用。按下第二个按钮后将其设置为 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;
}
}
}
}

关于java - 如何在 Action 监听器中获取多个JButton的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37450526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com