0

I am creating a grid of 4x4 buttons. I am trying to do this is in the controller. This is my code in initialize method.

    Button[][] gridButtons = new Button[4][4];
    for(int i=0; i<4; i++) {
        for (int j = 0; j<4; j++) {
            mainGrid.add(gridButtons[i][j], i, j);
            gridButtons[i][j].setText("1");
            gridButtons[i][j].minWidth(34.0);
            gridButtons[i][j].setMnemonicParsing(false);
            gridButtons[i][j].prefHeight(38.0);
            gridButtons[i][j].prefWidth(41.0);
            gridButtons[i][j].setTextAlignment(TextAlignment.CENTER);
        }
    }

The above code throws a NullPointerException at mainGrid.add(gridButtons[i][j], i, j);. But when I try to do the following, it works.

    Button gridButtons = new Button();
    gridButtons.setText("1");
    gridButtons.minWidth(34.0);
    gridButtons.setMnemonicParsing(false);
    gridButtons.prefHeight(38.0);
    gridButtons.prefWidth(41.0);
    gridButtons.setTextAlignment(TextAlignment.CENTER);
    mainGrid.add(gridButtons, 1, 1);

I'm not knowing what exactly is causing this issue.

1 Answer 1

4

When you create Button[][], you're creating the array of buttons. NOT the buttons inside the array. In other words, the array elements are still null after you create the array.

Simply add in gridButtons[i][j] = new Button(); as the first thing in your loop to initialize the Button and you should be good.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.