为了账号安全,请及时绑定邮箱和手机立即绑定

带秋千的井字游戏 - 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 关注
  • 140 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号