0

I made a slider (brightSlider) and I wanted to add it to the colorpicker. But I could not manage to add it, so I want it at least to be visible only the setup group (SetupGroup)is open.

So in draw(), I wrote a condition for that. But I am getting null pointer exception. I normally get this error when I don't initialize an object. But in this case, I don't know how to initialize a group. What can I do about this issue?

    import controlP5.*; //import ControlP5 library
    import processing.serial.*;
    
    Button button1;
    Group SetupGroup; //Should I somehow initialize this?

    void setup() { //Same as setup in arduino
    
      brightSlider = new BrightSlider(25,30,200,30,0,100); 

    Group SetupGroup = cp5.addGroup("SETUP")
    .setPosition(90,100)
    .setWidth(150)
    .setHeight(30)
    .setFont(font2);
//
//
//}

void draw() {  //Same as loop in arduino

 background(250);    // Setting the background to white

    if(mousePressed){
      brightSlider.checkPressed(mouseX,mouseY);
    }   

        if(SetupGroup.isOpen()){
        brightSlider.display();
        }
//
//
}

I get this error only when I write if(SetupGroup.isOpen()) line.

Here is the error:

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
noobie
  • 361
  • 2
  • 9
  • Just a small improvement for future questions: if you show a stack trace where line numbers appear, it is very helpful to have line numbers in the shown source code as well. And feel free to include the stack trace as text with code formatting, too… :-) – McPringle Aug 20 '21 at 12:10

2 Answers2

2
Group SetupGroup = cp5.addGroup("SETUP")
   .setPosition(90,100)
   .setWidth(150)
   .setHeight(30)
   .setFont(font2);

This declares an entirely new variable, also named SetupGroup. The method then ends, thus, this new local variable is immediately thrown away. Your field, named SetupGroup, remains null.

Just remove the Group in front. Type name; is declaring a new variable, and you can shortcut Type name; name = ...; to Type name = ...;.

name = ...; assigns new values to existing variables.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1
Group SetupGroup; //Should I somehow initialize this?

Yes!

An uninitialized field (except for primitives) in Java is equal to null.

Your code though tries to execute null.isOpen(), and because null is basically nothing, it doesn't have any methods. And trying to execute a method on a non-existing object results in a NullPointerException.

Benjamin M
  • 23,599
  • 32
  • 121
  • 201