首页 > 解决方案 > 在初始化之外禁用 JButton

问题描述

我正在创建我的Tic tac toe游戏,但我遇到了禁用JButton.

isThisTheEnd方法识别到游戏应该结束之后,我打算禁用所有按钮,但是在初始化之外是不可能的。有没有办法做到这一点,还有为什么可以为 textField 设置文本但不能设置启用?

完整代码

public void isThisTheEnd()
{
    //vertical
    for(int i=0;i<3;i++)
      if(board[0][i]==board[1][i] && board[1][i]==board[2][i])
            textEnd.setText((turn==1?"X":"O") + " wins!");

    //horizontal
    for(int i=0;i<3;i++)
       if(board[i][0]==board[i][1] && board[i][1]==board[i][2])
            textEnd.setText((turn==1?"X":"O") + " wins!");

    //diagonal
    if((board[0][0]==board[1][1] && board[1][1]==board[2][2]) || (board[2][0]==board[1][1] && board[1][1]==board[0][2]))
        textEnd.setText((turn==1?"X":"O") + " wins!");
    else 
        nextTurn();
}


 private void initialize() {

    btn1.setBackground(UIManager.getColor("Button.disabledForeground"));
    btn1.setBounds(36, 86, 120, 120);
    window.getContentPane().add(btn1);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    btn1.setBorder(new LineBorder(Color.WHITE));
    btn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            btn1.setText((turn==1?"X":"O"));
            board[0][0]=turn;
            isThisTheEnd();
            btn1.setEnabled(false);
        }
    });

}

标签: javatic-tac-toe

解决方案


// 编辑:问题是,变量是在函数内部定义的,不能在另一个函数中使用,请参阅此答案下方的评论。

这是旧的解决方案,与本例中的问题无关:

试试这个:

SwingUtilities.invokeLater(() -> {
  // Disable buttons here
});

推荐阅读