在初始化之外禁用 JButton
Disabling JButton outside initialize
我的 Tic tac toe
游戏即将创建完毕,但我遇到了禁用 JButton
的问题。
在 isThisTheEnd 方法识别出游戏应该结束后,我打算禁用所有按钮,但在 initialize[=24= 之外是不可能的].
有没有办法做到这一点,还有为什么可以为 textField 设置文本但不能为 setEnabled?
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);
}
});
}
// 编辑:
问题是,该变量是在函数内部定义的,不能在另一个函数中使用,请参阅此答案下方的评论。
这是旧的解决方案,与本例中的问题无关:
试试这个:
SwingUtilities.invokeLater(() -> {
// Disable buttons here
});
我的 Tic tac toe
游戏即将创建完毕,但我遇到了禁用 JButton
的问题。
在 isThisTheEnd 方法识别出游戏应该结束后,我打算禁用所有按钮,但在 initialize[=24= 之外是不可能的]. 有没有办法做到这一点,还有为什么可以为 textField 设置文本但不能为 setEnabled?
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);
}
});
}
// 编辑: 问题是,该变量是在函数内部定义的,不能在另一个函数中使用,请参阅此答案下方的评论。
这是旧的解决方案,与本例中的问题无关:
试试这个:
SwingUtilities.invokeLater(() -> {
// Disable buttons here
});