Douuga
Douuga

Reputation: 81

ArrayList error “NullPointerException”

I am changing array into arrayList, with several trials having error “NullPointerException”, the code is simplified as showed below, creating a rectangle when mousePressed. But still with the same error. What is the problem?

ArrayList textlines;

int xpos=20;
int ypos=20;

void setup() {
  size(1200, 768);
  ArrayList textlines = new ArrayList();
  //(Line)textlines.get(0) =textlines.add(new Line(xpos, ypos));
}

void draw() {
}


void mousePressed() {
  textlines.add(new Line(xpos, ypos));
  for (int i=0; i<textlines.size(); i++) {

    Line p=(Line)textlines.get(i);
    p.display();
  }
}


class Line {

  int x;
  int y;

  Line(int xpo, int ypo) {
    x =xpo;
    y =ypo;
  }

  void display() {
    fill(50, 50, 50);
    rect(x, y, 5, 5);
  }
}

Upvotes: 1

Views: 175

Answers (2)

Jordan Green
Jordan Green

Reputation: 18

I can see 3 things wrong with the above code: you are trying to declare the same thing twice, there is no variable/object declared in it (usually declared between the left and right arrows), and you have no number for your ArrayList, those are your problem.

You have two spaces where you can declare your ArrayList:

Space 1:

ArrayList textLines = new ArrayList();
void setup() {
  //Code goes in here.
}

Space 2:

ArrayList textLines;
void setup() {
  //other code goes here.
  textLines = new ArrayList();
}

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

You're likely shadowing the textlines variable here:

ArrayList textlines = new ArrayList();

Since you're re-declaring it in the setup() method. Don't do that. Declare it once in the class.

Specifically, check comments:

ArrayList textlines;

void setup() {
  // ...

  // *** this does not initialize the textlines class field
  // *** but instead initializes only a variable local to this method.
  ArrayList textlines = new ArrayList();

}

To fix it:

ArrayList textlines;

void setup() {
  // ...

  // *** now it does
  textlines = new ArrayList();

}

Upvotes: 5

Related Questions