1

I want to Fill a 2D-Array with Javafx Labels in Which I can change the Text when I click it. This is my actual Code but it's returning a NullPointer Exception.

Blockquote

`public static Label[][] initWelt() {
    Label[][] welt = new Label[DIM1][DIM2];
    for (int x = 1; x < welt.length - 1; x++) {
        for (int y = 1; y < welt.length - 1; y++) {
            if (Math.random() > 0.4) {
                welt[x][y].setText("X");
            }
            else{
                welt[x][y].setText(" ");
            }
        }
    }
    return welt;
}`
Gildarts
  • 13
  • 2
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – VGR Mar 21 '17 at 13:11

1 Answers1

2

it's returning a NullPointer Exception.

The only thing the below code does is initialise a two-dimensional array, it doesn't populate the two-dimensional array, hence the NullPointerException occurs.

Label[][] welt = new Label[DIM1][DIM2];

Basically you can't call this:

welt[x][y].setText("X");

without populating the two-dimensional array with object references.

to overcome the problem first populate the two dimensional array, something like below:

Label[][] welt = new Label[DIM1][DIM2];
for(int i = 0; i < DIM1; i++){
   for(int j = 0; j < DIM2; j++){
       welt[i][j] = new Label();
   }
}

then you can proceed with your current task at hand.

so now your code becomes like this:

public static Label[][] initWelt() {

    Label[][] welt = new Label[DIM1][DIM2];

    for(int i = 0; i < DIM1; i++){   //populate the array
        for(int j = 0; j < DIM2; j++){
            welt[i][j] = new Label();
        }
    }

    for (int x = 0; x < DIM1; x++) {
        for (int y = 0; y < DIM2; y++) {
            if (Math.random() > 0.4) {
                welt[x][y].setText("X");
            }
            else{
                welt[x][y].setText(" ");
            }
        }
    }
    return welt;
}

Note - personally I think it would be better to refactor the current method and insert the code that populates the two-dimensional array in a different method.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126