亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么每個按鈕的全局變量重置或不同?

為什么每個按鈕的全局變量重置或不同?

精慕HU 2021-06-30 09:00:29
我正在制作一個井字游戲,我希望能夠在單擊時讓按鈕交替 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;

不是globalJava 中的 a。到可以在Java中被理解為“全球”(通用于所有的類實例)模擬變量需要聲明它static

static boolean x = true;


查看完整回答
反對 回復 2021-07-14
  • 2 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號