java - 将对象存储在我的 2D 数组中并将其显示在 JFrame 上

标签 java arrays

嗨,ppeps(蹩脚的英语),

我正在开发一款 2D 迷宫游戏。我需要一些帮助来将对象存储在我的二维数组中。我在这个上得到一个 NullPointer:this.currentMap[colsCount][rowsCount] =objects.get(col);。主要调用 LevelGenerator 构造函数。

 public final class LevelGenerator extends JFrame {

private HashMap<String, ItemObject> objects = new HashMap<>();
private ItemObject[][] currentMap;
private int HEIGHT = 320;
private int WIDHT = 480;

public JFrame frame = null;

public Level currentLevel = null;

private final List<Level> levels
        = new ArrayList<Level>() {
            {
                add(new Level001());
                add(new Level002());
                add(new Level003());
            }
        };

public LevelGenerator() {
    // Vul de frame
    //this.frame = frame;
    // Vul de objecten lijst
    //objects.put("B", new Bazooka());
    objects.put("", new EmptyTile());
    objects.put("W", new Wall());
    this.currentLevel = levels.get(0);

    this.Load();
}

/// Laad de map in
public void Load() {
    int rowsCount = 0;
    int colsCount = 0;

    for (String[] row : this.currentLevel.map) {
        for (String col : row) {
            this.currentMap[colsCount][rowsCount] = objects.get(col);
            colsCount += 1;
        }

        rowsCount += 1;
    }

    this.Start();
}

public void Start() {

    this.frame.setSize(this.HEIGHT, this.WIDHT);
    this.frame.setLayout(new GridLayout(15, 10));
    this.frame.add(this.currentLevel);
    this.frame.setResizable(false);
    this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.frame.setVisible(true);

}
}

itemObject 代码:

public class ItemObject {

public int x = 0;
public int y = 0;

public String image = "";

public void setImage(String image) {
    this.image = image;
}

}

最佳答案

您尚未在任何地方初始化 ItemObject[][] currentMap。在方法 start() 中,您可以添加以下代码行:

currentMap = new ItemObject[*# of rows*][*# of columns*];

在向数组添加任何值之前,必须首先初始化该对象。

关于java - 将对象存储在我的 2D 数组中并将其显示在 JFrame 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37377230/

相关文章:

arrays - 使用rust "the trait ` std::array::LengthAtMost3 2` is not implemented"

java - 资源泄漏 : workbook is never closed warning when using Apache. POI XSSFWorkbook

java - 按每个字符串中的最后一个逗号拆分数组中的字符串

Java根据第一个数组的索引对第二个数组进行排序

java - 在 java 中将 Integer 或 String 数组作为参数传递

javascript - angularjs http post 到特定元素处的 json 数组

c - 为什么 *num 不显示第零个元素值?

java - 按条件将项目从一个集合插入到另一个集合,并使用 Google Guava 或 java 8 Stream API 迭代这两个集合

JavaFX 11 : IllegalAccessError when creating Label

javascript - Laravel 5/VueJS : Route for Get request route return Object or Array depending Eloquent query