我正在尝试使用JavaFX开发雷区游戏。我在创建雷区(板)实例并进行填充时遇到困难。在控制器中调用makeMinefield();后,minefield对象仍为null

(我没有包含的其余代码,因为它太长了,只包含了应该相关的内容。)

感谢您的任何建议。

在Minefield.java中

package fxMinesweeper;

public class Minefield {

    int minefieldWidth  = 10;           // starts at normal , default values
    int minefieldHeight = 10;           // should change when choicebox changes

    // grid amount of mines
    int gridEasyNumMines = 5;
    int gridNormalNumMines = 50;
    int gridHardNumMines = 190;

    int numMinesatStart;
    int numMinesLeft;
    int cellsUncovered;
    boolean exploded;
    Cell[][] minefield;

    public Minefield(){
        numMinesLeft = 0;
        numMinesatStart = 0;
        cellsUncovered = 0;
        exploded = false;
    }

    public void makeMinefield(){
        minefield = new Cell[minefieldWidth][minefieldHeight];
        for (int i = 0; i < minefieldWidth; i++) {
            for (int j = 0; j < minefieldHeight ; j++ ){
                Cell Cell = new Cell();             // make Cell
                minefield[i][j] = Cell;
                minefield[i][j].mined = false;
                minefield[i][j].flagged = false;
                minefield[i][j].x = i;
                minefield[i][j].y = j;
                System.out.println("Cell X = "
                      + minefield[i][j].x +": Y = "+ minefield[i][j].y +
                      ": Mined = "+ minefield[i][j].mined +": flagged : " +
                       minefield[i][j].flagged);
            }
        }
    }
}


在Controller.java中

package fxMinesweeper;

import javafx.beans.value.*;
import javafx.collections.FXCollections;
import javafx.event.*;       // in my code I do not have as many .* 's
import javafx.fxml.FXML;     // I used them here to lessen the imports
import javafx.scene.*;
import java.util.Timer;


public class MenuController implements EventHandler<ActionEvent>{
    Minefield minefield;
    public void initialize() {
        System.out.println("Begin Setup");
        Minefield minefield = new Minefield();
        minefield.makeMinefield();
    }
}

最佳答案

// here you declare an instance variable named minefield
Minefield minefield;

public void initialize() {
    System.out.println("Begin Setup");

    // here, instead of initializing the instance variable,
    // you declare a local variable with the same name
    // it should be: minefield = new Minefield();
    // or: this.minefield = new Minefield();
    Minefield minefield = new Minefield();
    minefield.makeMinefield();
}

08-18 15:46