gpt4 book ai didi

java - 井字游戏

转载 作者:行者123 更新时间:2023-11-30 09:08:54 25 4
gpt4 key购买 nike

出于个人学习目的,我正在用 Java 制作一个井字游戏,我正在尝试在单击按钮时将按钮的文本从“-”更改为“O”。显然我没有正确地处理它,一些提示将不胜感激。

当我运行代码时,我也收到错误“在 java.awt.AWTEventMulticaster.mouseEntered(未知来源)”

//includes graphics, button, and frame
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;


public static JButton [][] b = new JButton[3][3];

public static void playerMove(){
b[0][0].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
String text = b[0][0].getText();
if(text.equals("-")){
b[0][0].setText("O");
//computerMove();
}
else{
System.out.println("Pick Again");
playerMove();
}
}
});

}

最佳答案

您要做的是在程序开始时设置一个监听器,而不是在调用 playerMove 时。所以像这样

public static JButton [][] b = new JButton[3][3];
{ // Initialization code follows
b[0][0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = b[0][0].getText();
if(text.equals("-")){
b[0][0].setText("O");
computerMove();
}
else{
System.out.println("Pick Again");
} } });
// And so on for the other 8 buttons.
}

当然,您可能希望使用循环而不是将相似的代码重复 9 次,但是,正如您所说,那是另一个问题。

关于java - 井字游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23302586/

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