【问题标题】:Prevent same button from being clicked multiple times in tic tac toe game防止在井字游戏中多次单击同一按钮
【发布时间】:2015-04-18 21:58:16
【问题描述】:

我正在制作一个简单的井字游戏。在游戏中,轮到x还是o是由intturn决定的。这是 actionlistener 中的一段,展示了它是如何工作的。

public void actionPerformed(ActionEvent e){
   String command = e.getActionCommand();
   if (command.equals("b1")){
      //top row 1
      if (turn%2==0){
         b1.setText("X");
         turn ++;
         l1.setText("O's turn");
         x[0][0] = true;
      } else {
         b1.setText("O");
         turn ++;
         l1.setText("X's Turn");
         o[0][0] = true;              
      }
}

问题是,当我单击一个按钮并显示 x 或 o 时,其他玩家可以单击相同的按钮将位置从 x 更改为 o,反之亦然。我怎样才能阻止这种情况发生?

【问题讨论】:

    标签: java jbutton tic-tac-toe


    【解决方案1】:

    我建议您可以在单击按钮后禁用该按钮,使其不再可单击:

    更新

    if (command.equals("b1")){
            //top row 1
            if (turn%2==0){
                b1.setText("X");
                //add the following
    
                turn ++;
                l1.setText("O's turn");
                x[0][0] = true;
                turnNum ++;
                b1.removeActionListener(this);
            }
        } else {
            b1.setText("O");
            //add the following
    
            turn ++;
            l1.setText("X's Turn");
            o[0][0] = true;
            b1.removeActionListener(this);
    
    
        }
    

    【讨论】:

    • 当我添加 b1.enabled(false);它给了我一个错误,说找不到方法已启用(布尔值)
    • 对不起,我编辑了答案,应该是 setEnabled(false);它现在应该可以正常工作了
    • 它工作正常,但还有另一个问题。我设置了它,以便当单击按钮时字体为红色,当有人获胜时字体变为蓝色,但使用此方法时字体为灰色。我怎样才能让它再次变红
    • 好的,我再次编辑了答案,这应该同时满足这两种情况,现在看看。您可以尝试删除 ActionListener,使其不可点击,但保留您希望它具有的格式:)
    • 与以前相比有什么变化?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2013-05-18
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多