java - 在初始化之外禁用 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);
}
});
}
解决方案
// 编辑:问题是,变量是在函数内部定义的,不能在另一个函数中使用,请参阅此答案下方的评论。
这是旧的解决方案,与本例中的问题无关:
试试这个:
SwingUtilities.invokeLater(() -> {
// Disable buttons here
});
推荐阅读
- javascript - 从 gs 文件中的函数返回值到 javascript 文件 (HTML)
- http - 在不同的请求中获取相同的 html 正文
- python - 随着进度移动 qprogressbar 内的文本
- node.js - Node Js 从 URL 获取数据并传递给新变量
- java - 如何从 Android 中的可下载链接读取 CSV 文件
- c# - Asp.Net 多个 AuthenticationSchemas - 用户不会被重定向到 LoginPath Uri
- javascript - 无法更新 Pod 中的容器参数 - kuberneties -got 'pod 更新可能不会更改字段'
- android - Rocket.Chat Whitelabel Android 应用程序错误:此用户没有令牌
- sql - 如何将 SQL trn 文件转换为 bak 文件?
- javascript - 努力使用 Selenium 抓取网页动态代码