Not sure why I'm getting a NullPointerException when creating a Swing component
- by Alex
The error occurs when creating the Box object.
public void drawBoard(Board board){
for(int row = 0; row < 8; row++){
for(int col = 0; col < 8; col++){
Box box = new Box(board.getSquare(col, row).getColour(), col, row);
squarePanel[col][row].add(box);
}
}
Board is given from the Game constructor here (another class):
public Game() throws Throwable{
View graphics = new View();
board = new Board();
board.setDefault();
graphics.drawBoard(board);
}
The Board constructor looks like this:
public Board(){
grid = new Square[COLUMNS][ROWS];
for(int row = 0; row < 8; row++){
for(int col = 0; col < 8; col++){
grid[col][row] = new Square(this);
}
}
for(int row = 0; row < 8; row++){
for(int col = 0; col < 4; col++){
int odd = 2*col + 1;
int even = 2*col;
getSquare(odd, row).setColour(Color.BLACK);
getSquare(even, row).setColour(Color.WHITE);
}
}
}
And finally the Box class:
class Box extends JComponent{
Color boxColour;
int col, row;
public Box(Color boxColour, int col, int row){
this.boxColour = boxColour;
this.col = col;
this.row = row;
repaint();
}
public void paint(Graphics drawBox){
drawBox.setColor(boxColour);
drawBox.drawRect(50*col, 50*row, 50, 50);
drawBox.fillRect(50*col, 50*row, 50, 50);
}
}
So while looping through the array, it uses the two integers as coordinates to create the Box.
The coordinates are referenced and then repaint() is run.
The box also gets the colour, using the two integers, from the Square in the Board class.
Since the colour is already set, before the drawBoard(board) method is run, that shouldn't be a problem, right?
Exception in thread "main" java.lang.NullPointerException
at View.drawBoard(View.java:38)
at Game.<init>(Game.java:21)
at Game.main(Game.java:14)
The relevant part of Square
import java.awt.Color;
public class Square {
private Piece piece;
private Board board;
private Color squareColour;
public Square(Board board){
this.board = board;
}
public void setColour(Color squareColour){
this.squareColour = squareColour;
}
public Color getColour(){
return squareColour;
}