【问题标题】:NullPointerException when initialising a 2D array of BooleanProperty? [duplicate]初始化 BooleanProperty 的二维数组时出现 NullPointerException? [复制]
【发布时间】:2020-03-03 13:24:21
【问题描述】:

我有一个非常简单的构造函数,在其中我将 BooleanProperty 类型的二维数组初始化为全假。但是,我在grid[i][j].set(false) 行收到了 NullPointerException。我不确定为什么会这样,因为grid 不为空?我想我一定是错误地使用了 BooleanProperty,但我不确定为什么。

public class Game {
    private BooleanProperty[][] grid;

    public Game() {
        grid = new BooleanProperty[10][10];
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                grid[i][j].set(false);
            }
        }
    }

    // other methods
}

【问题讨论】:

  • grid[i][j] = new BooleanProperty() ?

标签: java javafx constructor


【解决方案1】:

即使您已经创建了BooleanProperty 引用数组,您也需要初始化每个引用。试试这个:

public class Game {
    private BooleanProperty[][] grid;

    public Game() {
        grid = new BooleanProperty[10][10];
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                BooleanProperty p = new SimpleBooleanProperty();
                p.set(false);
                grid[i][j] = p;
            }
        }
    }

    // other methods
}

【讨论】:

  • 跟进,BooleanProperty 是一个抽象类。最基本的实现类是 SimpleBooleanProperty。在大多数情况下,这可以解决问题。
【解决方案2】:

grid 不为空。它的内容是。所以添加这一行,你甚至不需要setter

grid[i][j] = new SimpleBooleanProperty(false); // Or whatever constructor or builder or factory method you want to use  

您已经为grid 对象分配了内存,但它本身是由其他对象组成的,而这些对象本身并没有被分配任何东西。因此,您还必须分别为它们分配内存。

【讨论】:

  • 当我尝试得到错误'无法实例化类型 BooleanProperty'?
  • BooleanProperty 是一个抽象类
  • 知道了,SimpleBooleanProperty 有效。谢谢!
  • @scott 请了解用于实例化BooleanProperty 并使用它的正确构造函数。它会解决你的问题
  • @NickClark 的回答对我有用
猜你喜欢
  • 2013-09-12
  • 1970-01-01
  • 2014-02-18
  • 2013-10-04
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
相关资源
最近更新 更多