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

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

帶秋千的井字游戲 - X 和 O 的不同顏色

帶秋千的井字游戲 - X 和 O 的不同顏色

慕田峪7331174 2021-12-22 19:29:35
我想為不同的玩家定制顏色;“X”和“O”。我初始化電路板的代碼在這里,我不明白為什么它不起作用。運行程序時,X 和 O 都是藍色的,即使我添加了 if/else if 循環也是如此。private void initializeBoard() {for(int i = 0; i < 3; i++) {  for(int j = 0; j < 3; j++) {    JButton button = new JButton();    button.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 100));    if(currentPlayer.equals("X")) {      button.setForeground(Color.BLUE);    }    else if (currentPlayer.equals("O")) {      button.setForeground(Color.RED);    }    board[i][j] = button;    button.addActionListener(new ActionListener() {      @Override      public void actionPerformed(ActionEvent e) {        if(((JButton)e.getSource()).getText().equals("") &&               hasWon == false) {          button.setText(currentPlayer);          hasWon();          choosePlayer();        }      }    });    pane.add(button);  }}}如果語言不打擾您,您可以在我的 GitHub 上查看整個代碼(我在這里將一些內容翻譯成英語,但在我的代碼中我使用了挪威語):https : //github.com/ibrarnaseer/Tic-Tac-Toe /樹/主人
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

看起來問題出在您設置前景色的位置。你需要把它設置在里面,ActionListener因為你知道選擇那個位置的玩家是誰。像這樣的東西:


private void initializeBoard() {

   for(int i = 0; i < 3; i++) {

      for(int j = 0; j < 3; j++) {

         JButton button = new JButton();

         button.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 100));

         board[i][j] = button;

         button.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

               if(((JButton)e.getSource()).getText().equals("") &&       

                  hasWon == false) {

                  button.setText(currentPlayer);

                  if(currentPlayer.equals("X")) {

                     button.setForeground(Color.BLUE);

                  } else if (currentPlayer.equals("O")) {

                     button.setForeground(Color.RED);

                  }

                  hasWon();

                  choosePlayer();

               }

            }

         });

         pane.add(button);

      }

   }

}


查看完整回答
反對 回復 2021-12-22
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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