gpt4 book ai didi

java - Java 访问 boolean 数组的方法

转载 作者:行者123 更新时间:2023-12-01 23:49:03 27 4
gpt4 key购买 nike

我有以下构造函数,它定义了一个 board 并检查是否单击了三个 JButton 中的任何一个:

Timer timer = new Timer(500, this);

private boolean[][] board;
private boolean isActive = true;
private int height;
private int width;
private int multiplier = 40;

JButton button1;
JButton button2;
JButton button3;
public Board(boolean[][] board) {
this.board = board;
height = board.length;
width = board[0].length;
setBackground(Color.black);
button1 = new JButton("Stop");
add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isActive = !isActive;
button1.setText(isActive ? "Stop" : "Start");
}
});
button2 = new JButton("Random");
add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
this.board = randomBoard();
}
});
button3 = new JButton("Clear");
add(button3);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
this.board = clearBoard();
}
});
}

但它返回此错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
board cannot be resolved or is not a field
board cannot be resolved or is not a field

这是为什么呢?如何在构造函数中访问 this.board

最佳答案

该问题是由于您尝试访问匿名内部类中的 this.board 引起的。由于没有定义 board 字段,因此会导致错误。

例如:

button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
this.board = randomBoard();
}
});

为了能够在匿名内部类中使用 board 变量,您需要删除 this 或使用类似 Board.this.board 的内容(如果你想更明确的话)。

关于java - Java 访问 boolean 数组的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16547310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com