Java Tic Tac Toe带摆动-X和O的不同颜色
我想为不同的玩家定制颜色;X和O。 我初始化电路板的代码在这里,我不明白为什么它不工作。运行程序时,X和O都是蓝色的,即使我添加了if/else if循环Java Tic Tac Toe带摆动-X和O的不同颜色,java,swing,Java,Swing,我想为不同的玩家定制颜色;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
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上查看整个代码。我在这里将一些东西翻译成了英语,尽管在我的代码中我使用了挪威语:看起来问题在于你在哪里设置前景颜色。您需要在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);
}
}
}
if块需要在ActionListener中。当按钮被创建时,当前播放器将是X,并且只有X。当按下按钮时,不会神奇地重新调用该创建代码和if块,除非再次将其放入动作侦听器中。