Search code examples
javaprocessing

Why am I getting this error in Processing?


In the middle of trying to create a drawing program here where the brush changes colour depending on position of mouseX and mouseY.

Keep receiving this error when I run code:

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
RuntimeException: java.lang.reflect.InvocationTargetException
at processing.core.PApplet.runSketch(PApplet.java:10852)
at processing.core.PApplet.main(PApplet.java:10620)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at processing.core.PApplet.runSketch(PApplet.java:10846)
... 1 more
Caused by: java.lang.NullPointerException
at processing.core.PApplet.fill(PApplet.java:14781)
at sketch_220306a.<init>(sketch_220306a.java:40)
... 6 more

Appreciate any help... I am quite new to Java so you might want to explain it in more basic terminology explaining why I need to change something.

/* [Create a drawing program where the 'brush' changes colour depending on the position in the window.] */

void setup () {
    background (128); // set background colour
    mouseX = 50; // declare initial mouse X value
    mouseY = 50; // declare initial mouse Y value
}

void draw () {
    ellipse(mouseX, mouseY, 10, 10); // 
} 
// if the value of mouseX is greater than 50 and mouseY is less than 50
{ if ((mouseX > 50) && (mouseY < 50)) {
    // fill ellipse red
    fill (255,0,0); 
} else { 
    // fill ellipse blue
    fill (0,0,128); 
}

}


Solution

  • I'm not sure what the InvocationTargetException is about. However, there are some syntax errors with the code in your question. Here is the code, fixed:

    void setup () {
      background (128); // set background colour
      mouseX = 50; // declare initial mouse X value
      mouseY = 50; // declare initial mouse Y value
    }
    
    void draw () {
      // if the value of mouseX is greater than 50 and mouseY is less than 50
      if ((mouseX > 50) && (mouseY < 50)) {
        // fill ellipse red
        fill (255,0,0); 
      } else { 
        // fill ellipse blue
        fill (0,0,128); 
      }
      ellipse(mouseX, mouseY, 10, 10);
    }
    

    I changed the locations of some of the curly braces, and moved the ellipse to be after you set the color.