在不使用嵌套循环的情况下,在JButton [] []数组中查找ActionEvent的源? [英] Finding the source of an ActionEvent in a JButton[][] array without using nested loops?
问题描述
我创建了一个JFrame
应用程序,其中JButtons[][]
的8x8数组与选定的&数组相对应.取消选择ImageIcon
s.当按下按钮时,它将使用setSelection()
选择该按钮,然后取消选择其他任何按钮.但是,如果按下了与所选按钮相邻的任何按钮,则所选按钮和相邻按钮将交换ImageIcons
.
I've created a JFrame
application with an 8x8 array of JButtons[][]
corresponding to an array of selected & deselected ImageIcon
s. When a button is pressed, it selects that button using setSelection()
and deselects any other buttons. However, If any button adjacent to the selected button is pressed, the selected button and the adjacent button will swap ImageIcons
.
我已经成功地完成了大部分操作,但是使用ActionEvent
中的嵌套循环来确定相邻的按钮,选定的按钮和取消选定的按钮同时成为逻辑上的噩梦.
I've successfully managed to do most of this, however using nested loops within an ActionEvent
to determine adjacent buttons, the selected button, and deselected buttons simultaneously becomes a logical nightmare.
public void actionPerformed(ActionEvent event)
{
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (event.getSource() == buttons[row][col]) {
if (row<7) buttonsAdjacent[row+1][col] = true;
if (row>0) buttonsAdjacent[row-1][col] = true;
if (col<7) buttonsAdjacent[row][col+1] = true;
if (col>0) buttonsAdjacent[row][col-1] = true;
buttons[row][col].setSelected(true);
}
}
}
}
如何将actionListeners
放入数组索引[row][col]
的每个相邻按钮中,以确定是否实际按下了某个相邻按钮?每次选择新按钮后,我如何重新分配那些actionListeners
?
How can I put actionListeners
into each adjacent button at array index [row][col]
to determine if an adjacent button has actually been pressed? And how can I reassign those actionListeners
every time a new button has been selected?
推荐答案
如完整的示例所示,您可以对于给定的网格大小,计算JButton
在List<JButton>
中的索引作为行和列的函数,例如N * N
.请参阅注释和编辑历史记录以了解替代方法.
As shown in this complete example, you can calculate the index of a JButton
in a List<JButton>
as a function of the row and column for a given grid size, e.g. N * N
. See the comments and edit history for alternatives.
private static final int N = 5;
private JButton getGridButton(int r, int c) {
int index = r * N + c;
return list.get(index);
}
这篇关于在不使用嵌套循环的情况下,在JButton [] []数组中查找ActionEvent的源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!