【发布时间】:2019-02-10 09:36:24
【问题描述】:
我正在用 Java 创建一个国际象棋游戏,它需要创建一个 2D 对象数组来制作棋盘。数组在创建时显示为其中包含所有对象,但是当我从不同的对象调用不同的方法时,数组突然充满了空值。
这是在 Java 中,包括在 Eclipse 中运行的一些 JavaFX(我认为 JavaFX 不会影响任何东西,但它被标记以防万一)。我试过在多个位置打印数组,它只在 createBoard() 中有效,而不是 setBoard()(或 GUI 的 startGame() 方法。
public class ChessGame {
public static void main(String[] args) {
GUI gui = new GUI();
Application.launch(GUI.class, args);
Player player1 = new Player();
Player player2 = new Player();
gui.startGame(player1, player2);
}
}
public class GUI extends Application {
Board chessBoard = new Board();
@Override
public void start(Stage primaryStage) {
GridPane chessBoardPane = chessBoard.createBoard();
primaryStage.setScene(new Scene(chessBoardPane, 400, 400));
primaryStage.show();
}
public void startGame(Player player1, Player player2) {
//printing the array here still produces nulls.
chessBoard.setBoard(player1, player2);
}
}
public class Board {
private BoardSquare[][] boardArray;
public static int boardSize = 8;
//private GridPane boardGrid = null;
public Board() {
boardArray = new BoardSquare[boardSize][boardSize];
}
public GridPane createBoard() {
GridPane chessBoard = new GridPane();
for (int x = 0; x < boardSize; x++) {
for (int y = 0; y < boardSize; y++) {
StackPane square = new StackPane();
String color;
if ((x + y) % 2 == 0) {
color = "white";
} else {
color = "black";
}
square.setStyle("-fx-background-color: " + color + ";");
chessBoard.add(square, y, x);
boardArray[x][y] = new BoardSquare(x, y, color, square, null);
}
}
for (int i = 0; i < boardSize; i++) {
chessBoard.getColumnConstraints().add(new ColumnConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, HPos.CENTER, true));
chessBoard.getRowConstraints().add(new RowConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, VPos.CENTER, true));
}
//at this point, printing the x and y values of the array is possible.
return chessBoard;
}
public void setBoard(Player player1, Player player2) {
Player currentPlayer = player1;
for (int x = 0; x < boardSize; x++) {
for (int y = 0; y < boardSize; y++) {
//if (boardArray[x][y] != null) { <-- error occurs if removed
if (y == 0) {
if (x == 0 || x == 7) {
Rook rook = new Rook(currentPlayer);
boardArray[x][y].setPiece(rook); //<-- error
}
//etc.
在 createBoard 中打印 boardArray 的 x 和 y 值会打印出预期的 8x8 网格的坐标。移至 setBoard() 时,boardArray 仍应充满 BoardSquare 值,但现在突然间所有值都为空,并且尝试打印数组的 x 和 y 值无济于事。我不知道为什么数组突然空了。
【问题讨论】:
-
boardArray的元素仅设置在createBoard()内(通过boardArray[x][y] = new BoardSquare行)。但是这个createBoard()永远不会被调用。
标签: java arrays javafx nullpointerexception