如何确定按钮数组中的哪个按钮被单击? [英] How do I tell which button is being clicked in an array of buttons?
问题描述
我有一个希望使用的二维按钮阵列.当我想调用actionListener时,如何知道我的2D数组中的哪个按钮索引被单击?这是我第一次与听众打交道,因此,如果可以的话,请从更基本的角度进行解释.
I have an 2D array of buttons that I wish to use. When I want to call an actionListener, how to I tell which button index in this 2D array of mine is being clicked? This is my first time dealing with a listener, so please explain this on a more basic level if you can.
以下是我如何在网格(12x12)上布置按钮的一些代码
Here is some code of how I have my buttons laid out on a 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,但我不知道该怎么做才能使按下按钮并将其与周围的其他按钮进行比较.我想提到我正在处理静态方法.
These buttons are randomly assigned a color from an array of colors created earlier. I now have to override actionlistener and I don't know how to do that in a way which allows me to get the button being pressed and compare it to other buttons around it. I would like to mention that I am dealing with static methods.
推荐答案
首先,您应该通过 addActionListener()
方法向动作监听器注册所有按钮.然后,在 actionPerformed()
方法中,应调用 getSource()
以获取对所单击按钮的引用.
First of all you should register all of your buttons with an actionlistener by this method addActionListener()
. Then within the actionPerformed()
method you should call getSource()
to get a reference to the button which was clicked.
选中此帖子
无论如何这里是代码,gameButtons [] []数组必须全局可用
Anyway here is the code, The gameButtons[][] array has to be available globally
//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
}
}
}
}
这篇关于如何确定按钮数组中的哪个按钮被单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!