如何获得按钮的数组#/使此运行更有效

时间:2011-05-17 22:47:17

标签: java arrays jbutton delay

我正在制作一个复杂的tic tac toe程序,它具有可变的网格大小和玩家数量。但是我的一位朋友评论说,他们在64乘64的空间中移动后反应有点慢。我查看了它,我发现了问题,我的程序检查网格中的每个按钮,看它是否被点击,然后它检查每个玩家,看看谁做了移动。一旦它找到了两个,它继续生活:D。但是,使用更大的网格可能需要一些时间。所以我试图通过加入一些“休息”来修复它,但他们没有帮助更快地找到它,只是为了停止看起来更快。

public void actionPerformed(ActionEvent gridButtonClicked) {
        for (int i = 0; i < gridButton.length; i++) {
            if (gridButtonClicked.getSource() == gridButton[i]) {
                for(int a = 0;a < amountOfPlayers;a++){
                    if(turn == a) {
                        gridButtonOwner[i] = a + 1;
                        gridButton[i].setBackground(playerColors[a]);
                        gridButton[i].setEnabled(false);
                        System.out.println("Grid " + i + ": " + gridButtonOwner[i]);
                        break;
                    }
                }
                break;
            }
        }
    }

我想知道的是,如果我可以点击按钮的数组编号。就像gridButtonClicked = gridButton [1]一样,它将返回数字1,或者如果它等于gridButton [2],它将返回2,等等。

  • gridButtonOwner是一个int数组,
  • gridButton是一个jbutton数组。

2 个答案:

答案 0 :(得分:3)

我必须说我不理解循环的必要性。在第一个for循环中你得到了网格按钮 - 但是你知道这是什么,因为它是事件源......你可以将GridButton的地图存储到Integer中以获得你的数组中的位置。为什么循环找到它?在第二个循环中,您将循环到a == turn ...这意味着您已经知道a是什么,因为它== turn。您应该能够完全删除循环:

// earlier on: myMap = new HashMap<GridButton, Integer>();
public void actionPerformed(ActionEvent gridButtonClicked) {
    GridButton gridButton = gridButtonClicked.getSource();
    int i = myMap.get(gridButton);
    gridButtonOwner[i] = turn + 1;
    gridButton.setBackground(playerColors[turn]);
    gridButton.setEnabled(false);
    System.out.println("Grid " + i + ": " + gridButtonOwner[i]);
}

答案 1 :(得分:1)

如果使用HashMap,您可以在单个查找中找到索引“i”(无需循环)。 你必须使用正确的类型(例如JButton,我不知道你使用哪个代替GridButton)。

HashMap<GridButton, Integer> buttonIndices = new HashMap<GridButton, Integer>();

'Integer'是对象版本,如果'int',因为集合不能存储基本类型。

然后用每个GridButton和索引值填充地图(填写...):

for (i...) {
  buttonIndices.put(gridButton[i], i); // the 'i' is auto-converted to Integer
}

为gridButton查找'i':

Integer index = buttonIndices(gridButton);
if (index == null) {
  // error, not found
  error handling stuff...
}

i = index; // converts Integer to int type of 'i'

这应该让你朝着正确的方向前进。