cp5 causing nullpointer exception
in
Contributed Library Questions
•
1 year ago
in draw i have:
- for (Field f : fields) {
- f.createField((int)random(10, 50), 20);
- }
the cp5 slider does the same thing.
However, with cp5 it can happen that it triggered createField(.....) while it's also at something() in draw.
This is causing a null pointer example (just go forward and backward with the slider untill it happens).
How can i avoid this (multiple suggestions please).
I know one that is really time consuming and ugly.
- import controlP5.*;
- ControlP5 cp5;
- ControlWindow cwindow;
- ArrayList<Field> fields = new ArrayList<Field>();
- void setup() {
- size(400, 400);
- smooth();
- for (int i = 0; i < 20; i++) {
- fields.add(new Field());
- }
- cp5 = new ControlP5(this);
- cwindow = cp5.addControlWindow("stuff", 100, 100, 500, 400);
- cp5.addSlider("xSteps")
- .setValue(10)
- .setRange(1, 50)
- .moveTo(cwindow);
- }
- // . . . . . . . . . . . . . . . . . . .
- void draw() {
- background(255);
- // it never crashes by this
- for (Field f : fields) {
- f.createField((int)random(10, 50), 20);
- }
- for (Field f : fields) {
- text(f.something(), 20, 20);
- }
- }
- // . . . . . . . . . . . . . . . . . . .
- // but slider does
- void xSteps(int xSteps) {
- for (Field f : fields) {
- f.createField(xSteps, 100);
- }
- }
- // . . . . . . . . . . . . . . . . . . .
- class Field {
- PVector[][] field;
- int xSteps, ySteps;
- Field() {
- createField(100, 100);
- }
- // . . . . . . . . . . . . . . . . . . .
- void createField(int xSteps, int ySteps) {
- this.xSteps = xSteps;
- this.ySteps = ySteps;
- field = new PVector[xSteps][ySteps];
- for (int x = 0; x < xSteps; x++) {
- for (int y = 0; y < ySteps; y++) {
- field[x][y] = new PVector();
- }
- }
- }
- // . . . . . . . . . . . . . . . . . . .
- float something() {
- return field[xSteps-1][ySteps-1].x;
- }
- // . . . . . . . . . . . . . . . . . . .
- }
1