我创建了一个包含动作监听器的按钮。我在动作侦听器外部声明了变量。但是我不能在actionlistener中更改变量内容。我总是收到错误消息:从内部类引用的局部变量必须是final或有效的final
我该如何解决问题?
我希望代码部分对您足够好。
我已经尝试过:
final int player = 1;
但是我不能用final更改内容。
public void Game(char[] gamefield) {
int player = 1;
TickTackToeSpieleablauf window = new TickTackToeSpieleablauf();
btnSpielebrett1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Field1
int field = 0;
boolean geklappt = false;
geklappt = window.playervsplayer(gamefield, field, player);
System.out.println(gamefield[0]);
if (geklappt && player == 1){
gamefield[field] = 'x';
player = 2; <----- HERE I GET THE ERROR
}else if(geklappt && player == 2){
gamefield[field] = 'o';
}else if(!geklappt){
if (gamefield[0] != '1' && gamefield[1] != '2' &&gamefield[2] != '3' && gamefield[3] != '4' &&gamefield[4] != '5' && gamefield[5] != '6' &&gamefield[6] != '7' && gamefield[7] != '8' &&gamefield[8] != '9'){
//Gamefield full, array clear;
gamefield[0] = '1';
gamefield[1] = '2';
gamefield[2] = '3';
gamefield[3] = '4';
gamefield[4] = '5';
gamefield[5] = '6';
gamefield[6] = '7';
gamefield[7] = '8';
gamefield[8] = '9';
}
}else{
System.out.println("Feld bereits belegt.");
}
}
答案 0 :(得分:1)
Ypu可以为您的player
值提供包装类,例如:
class Player {
int value = 1;
}
并使用对此类的引用而不是原始类型:
final Player player = new Player();
...
if (geklappt && player.value == 1){
gamefield[field] = 'x';
player.value = 2;
}