我正在制作一個井字游戲,我希望能夠在單擊時讓按鈕交替 x 和 o。現在它們在第一次點擊時都是 x ,在第二次點擊時都是 o 。我也嘗試過使用和不使用關鍵字 this 。這是按鈕類public class Toebuttons extends JButton implements ActionListener{boolean x = true; // if true x's turn if false o's turnint count = 0;public Toebuttons(){ super("blank"); this.addActionListener(this);}public void actionPerformed(ActionEvent e){ if(this.x == true) { count++; System.out.println(count); setText("X"); this.x = false; } else if(this.x == false) { count++; System.out.println(count); setText("O"); this.x = true; } }}這是板類public class ticTacBoard extends JFrame{Toebuttons toe[] = new Toebuttons[9];public ticTacBoard(){ super("Tic tac board"); setSize(500,500); setLayout(new GridLayout(3,3)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); toFront(); for(int i = 0; i<toe.length; i++) { toe[i] = new Toebuttons(); add(toe[i]); } setVisible(true); }}
2 回答

UYOU
TA貢獻1878條經驗 獲得超4個贊
這不是 C++ 而是這個
boolean x = true;
不是global
Java 中的 a。到可以在Java中被理解為“全球”(通用于所有的類實例)模擬變量需要聲明它static
像
static boolean x = true;
添加回答
舉報
0/150
提交
取消