gpt4 book ai didi

Java Action 监听器

转载 作者:行者123 更新时间:2023-11-30 06:31:05 25 4
gpt4 key购买 nike

我正在使用 Netbeans 在 Java 上制作井字游戏。我有一个带按钮的 3x3 板布局。单击某个按钮时,该按钮将被禁用,并且字母“X”或“O”将显示为该按钮的标签。当我测试我的游戏时,连续获得 3 个“X”。在我点击另一个按钮之前,它不会说我赢了。因此,直到我单击另一个按钮之前,它不会响应我赢了。我应该使用鼠标释放事件吗?

最佳答案

gameOver 应最后调用,因为在您更新按钮之前,您不会知道是否已达到获胜条件

您还可以通过使用操作源来大大减少代码

public class Listener implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
JButton btn = (JButton)source;
btn.setEnabled(false);
btn.setFont(new Font("Courier New", Font.BOLD, 56));
counter++;
if(counter % 2 == 0 && counter < 10){
btn.setText("O");
gameText.setText("X's Turn!");
} else {
btn.setText("X");
gameText.setText("O's Turn!");
}
gameOver();
}
}

您的 gameOver 检查有些有限,您可能有 look at this example用于确定连接4中是否获胜条件,但想法是相同的。

如果您愿意,this example将这个想法应用到井字游戏

关于Java Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com