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



我正在使用图片和 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 类提供私有字段,即使它是匿名内部类,其中一个字段可以是对按下的最后一个按钮的引用。按下第二个按钮后将其设置为 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;
            }
        }
    }
}

最新更新