NullPointerException - JavaFX


Question

I am getting NullPointerException in this code. I am using JavaFX 2.2 , NetBeans IDE 7.3.1, Windows 8, Java 1.7.0

    public class SampleController implements Initializable {
    @FXML
    GridPane grid;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        for(int i=0;i<10;i++){
            for(int j=0;j<4;j++){
                AnchorPane tile = new AnchorPane();
                tile.setMaxSize(225, 225);
                grid.add(tile, j, i);
            }
        }
    }
}

-JavaFX 2.2

1
0
12/20/2013 12:14:13 PM

Accepted Answer

My guess is that your GridPane isn't initialized. This would happen if you e.g. have a different ID for it in your FXML file.

It's a likely cause of the error, but I can't be sure without the full code.

Also,

you should learn how to debug a NullPointerException. It's often very simple. Here's something to get you started:

  1. Read the stack trace. Its first line looks something like this:

Exception in thread "main" java.lang.NullPointerException. And if you don't see one or it doesn't give you any information, make sure you haven't caught the exception you're getting.

  1. Find out what's null and where (the stack trace comes with line numbers.)
  2. Fix it (this usually means initializing something uninitialized, as in your case)

And you might want to look up how to debug java programs in general (logging, stepping through your code at runtime etc). I've written a short (beginner's) blog post on the subject.

12
5/23/2017 12:10:38 PM

Several reason can cause this problem. 1. GridPane has @FXML tag which means it should be initialized with fxml loader, one possible reason is that you have not given the id of grid to GridPane in scenebuilder. 2. Another reason could be to specify the name of the FXML controller incorrectly. So you have to specify correct name of the package (if controller is not in default package) followed by (.) and controller name.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon