如何在动作侦听器中获取多个 JButton 的来源?

How to get the source of multiple JButtons in action listener?

我正在使用图片和 JButton 数组编写记忆匹配游戏,但是当我尝试比较两个被单击的按钮时,我 运行 遇到了问题。你如何存储索引 of/get 第二个按钮的索引?据我所知,按钮数组中的所有按钮都链接到同一个 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);

     }
 }

此外,在我的面板 class 中,我试图做类似的事情,但最终将它移到了显示 class 上,因为面板无法访问按钮数组。

  //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 提供 class 私有字段,即使它是一个匿名内部 class,其中一个字段可以是对最后按下的按钮的引用。在按下第二个按钮后将其设置为空,您将始终知道按下的按钮是针对第一个按钮还是第二个按钮。

例如,

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;
            }
        }
    }
}