如何判断按钮数组中的哪个按钮被点击?

时间:2012-11-25 04:30:54

标签: java arrays swing jbutton actionlistener

  

可能重复:
  How to get X and Y index of element inside GridLayout?

我有一个我希望使用的2D按钮阵列。当我想调用一个actionListener时,如何判断我的二维数组中的哪个按钮索引被点击?这是我第一次与听众打交道,所以如果可以的话,请在更基础的层面上解释一下。

以下是我如何将我的按钮布置在gride(12x12)上的一些代码

//A loop to add a new button to each section of the board grid.
for (int i = 0; i < gridSize; i++) {
  for (int j = 0; j < gridSize; j++) {
    gameButtons[i][j] = new JButton();
    gameButtons[i][j].setBackground(colors[(int)(Math.random() * numColors)]);
    boardGrid.add(gameButtons[i][j]);

    try {
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    }
    catch (Exception e) {
    }

  }
}

这些按钮是从前面创建的颜色数组中随机分配的颜色。我现在必须覆盖actionlistener并且我不知道如何以允许我按下按钮并将其与其周围的其他按钮进行比较的方式来执行此操作。我想提一下,我正在处理静态方法。

3 个答案:

答案 0 :(得分:3)

首先,您应该使用此方法addActionListener()向actionlistener注册所有按钮。然后在actionPerformed()方法中,您应该调用getSource()来获取对点击按钮的引用。

选中此post

无论如何这里是代码,gameButtons [] []数组必须全局可用

//A loop to add a new button to each section of the board grid.
for (int i = 0; i < gridSize; i++) 
{
  for (int j = 0; j < gridSize; j++) 
  {
    gameButtons[i][j] = new JButton();
    gameButtons[i][j].addActionListener(this);
    gameButtons[i][j].setBackground(colors[(int)(Math.random() * numColors)]);
    boardGrid.add(gameButtons[i][j]);

    try {
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { } 
  }
}

//--------------------------------------------------------


@Override
public void actionPerformed(ActionEvent ae)
{
  for (int i = 0; i < gridSize; i++) 
  {
    for (int j = 0; j < gridSize; j++) 
     {
       if(ae.getSource()==gameButtons[i][j]) //gameButtons[i][j] was clicked
       {
             //Your code here
       }
     }
  }
}

答案 1 :(得分:2)

如果您想避免再次循环遍历数组,您也可以将索引存储在JButton中。

JButton button = new JButton();
button.putClientProperty( "firstIndex", new Integer( i ) );
button.putClientProperty( "secondIndex", new Integer( j ) );

然后在ActionListener

JButton button = (JButton) actionEvent.getSource();
Integer firstIndex = button.getClientProperty( "firstIndex" );
Integer secondIndex = button.getClientProperty( "secondIndex" );

答案 2 :(得分:1)

如果您需要按下按钮的索引,请尝试以下操作:

private Point getPressedButton(ActionEvent evt){
    Object source = evt.getSource();
    for(int i = 0; i < buttons.length; i++){
        for(int j = 0; j < buttons[i].length; j++){
            if(buttons[i][j] == source)
                return new Point(i,j);
        }
    }
    return null;
}

然后你可以通过

提取值
Point p = getPressedButton(evt);

这意味着:

  
    
      

按下按钮==按钮[p.x] [p.y]

    
  

否则,通过简单的电话evt.getSource();完成工作。

相关问题