I can not figure out why the return value for method getButton is null.
I am trying to create a maze game. The setUp method, in the MazeFrame, class draws the maze. Each step within the maze is a button which, in this program, is a Step object which extends JButton.
I need the getButton method to work, so I can call it in other classes and refer to a particular step/button by its index, but this method is bent on always returning null, instead of the correct button I am referring to.
The only time it does not return null is when I call it with a = 6, b = 6, which is the step.length - 1. Then it returns the correct button.
I tried creating an ArrayList where I stored each Step/Button as soon as they were created. Then I had the getButton method run through this array list and return the step within it that had the same index values (a and b, i and j, row and column) as the index values passed into getButton.
The return value is still null.
public class MazeFrame extends JFrame {
Container contentPane;
private int buttonCount = 7;
private Step[][] steps;
private ArrayList<Step> locations = new ArrayList<>();
public static void main(String[] args) {
FirstMaze thisOne = new FirstMaze();
thisOne.SetUp();
thisOne.pack();
thisOne.setVisible(true);
thisOne.setSize(new Dimension(400, 400));
}
public void SetUp() {
//sets up container and sets layout grid
contentPane = this.getContentPane();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.setLayout(new GridLayout(buttonCount, buttonCount));
//run through the grid
for (int i = 0; i < buttonCount; i++) {
for (int j = 0; j < buttonCount; j++) {
steps = new Step[buttonCount][buttonCount];
//create and add buttons to the container
//for the start button
if (i == 0 && j == 0) {
contentPane.add(steps[i][j] = new Step(i, j, "start", this));
}
//for the goal button
else if (i == buttonCount - 1 && j == buttonCount - 1) {
contentPane.add(steps[i][j] = new Step(i, j, "goal", this));
}
//every other button
else {
contentPane.add(steps[i][j] = new Step(i, j, "intermediary", this));
}
steps[i][j].setTransitions(steps[i][j].getTransitions(i, j));
getButton(i, j); //call to getButton
}
}
}
public Step getButton(int a, int b) {
System.out.println("is the step: a,b null? " + (steps[a][b] == null)); //Print statement is a test
return steps[a][b];
}
}
The print statement in getButton is a test, and it confirms that the return value is null.
Your for loop to initialize the array either needs to be placed in a constructor or enclosed in curly brackets to use it as an initialization block.
If your code is within a static class, you need to mark your initialization block as static, too.
Personally, I recommend putting this code in a constructor method.