Newby question :Null Pointer Exception Error

Hey folks, I am trying to write a code that draws a circle on every point that mouse is pressed and when mouse is released the circle moves to center of screen and merges with a big circle in the center. I wrote its code without any class objects and it works fine( 1st code) but when I try to write it with class objects(2nd code in comments) I face Null Pointer Exception error and I am almost sure that I have initialized all variables. I would appreciate if you tell me what is wrong.

int r;
int R = 100;
int RL = 100;
int x;
int y;
void setup() {
  size(800, 800);
  smooth();
  background(255);
  noStroke();
  frameRate(30);
  ellipseMode(CENTER);
}
void draw() {
  background(255);
  fill(80);
  ellipse(width/2, height/2, R, R);
  if (mousePressed) {
    fill(0);
    r++;
    x = mouseX;
    y = mouseY;
    ellipse(x, y, r, r);
  } else {
    fill(80);
    x += (width/2-x)*.05;
    y += (height/2-y)*.05;
    ellipse(x, y, r, r);
    if (abs(x-(width/2))<20 && abs(y-(height/2))<20 && r>0) {
      R++;
      ellipse(width/2, height/2, R, R);
      if (R == RL+r) {
        RL = R;
        r = 0;
      }
    }
  }
  println(r);
}
Tagged:

Answers

  • edited August 2017

    And this a the code with problem:

    int R = 100;
    mCircle Circle;
    
    void setup() {
      size(800, 800);
      smooth();
      background(255);
      noStroke();
    
      frameRate(30);
      ellipseMode(CENTER);
      ellipse(width/2, height/2, R, R);
    }
    
    void draw() {
      background(255);
      if (mousePressed) {
    
         Circle.create();
         Circle.move();
      }
    }
    
    class mCircle {
      int r = 1;
      int x;
      int y;
      void create() {
        x = mouseX;
        y = mouseY;
        ellipse(x, y, r, r);
        r++;
      }
    
      void move() {
        x += (width/2-x)*.05;
        y += (height/2-y)*.05;
        ellipse(x, y, r, r);
      }
    }
    
  • edit post, highlight code, press ctrl-o to format.

    Null Pointer Exception FAQ:

    https://forum.processing.org/two/discussion/8071/why-do-i-get-a-nullpointerexception

  • where do you instantiate Circle?

  • where do you instantiate Circle?

    In line 2 at the top.

  • Answer ✓

    no, that defines it, doesn't instantiate it. println(Circle); will show that it's null and so line 19 is a NPE.

    somewhere (setup()) you need Circle = new mCircle();. read the link.

    also, read up on java naming convention because you've got it all backwards.

  • Thank you koogs!

Sign In or Register to comment.