NullPointerException when calling textWidth in another class


I currently am working on a project using eclipse and have been getting a NullPointerException Error. I was able to mimic this in a small program with the stack provided below. The error in this example is coming from this.textSize = textWidth(name.charAt(0)); where the nullpointer is then saying it is coming from textWidth within PApplet. The stacktrace is provided below as well:


package testproject;

import processing.core.PApplet;
import processing.core.PFont;

public class TestProject extends PApplet {

    PFont p;
    TestClass1 test;

    public void setup() {
        size(500, 500);

        p = createFont("Times-Roman", 40);
        textFont(p, 40);

    public void draw() {
        ellipse(100, 100, 100, 100);

    public void testFunction(){
        test = new TestClass1("testString");

TestClass1 File:

package testproject;

import processing.core.PApplet;

public class TestClass1 extends PApplet{

    String name;
    float textSize;

    TestClass1(String name){ = name;
        this.textSize = textWidth(name.charAt(0));

and the stacktrace:

Exception in thread "Animation Thread" java.lang.NullPointerException
    at processing.core.PApplet.textWidth(
    at testproject.TestClass1.<init>(
    at testproject.TestProject.testFunction(
    at testproject.TestProject.setup(
    at processing.core.PApplet.handleDraw(
    at processing.core.PGraphicsJava2D.requestDraw(
    at Source)

I found another person with a similar issue: But even setting textSize in setup still showed an error.

Any help would be greatly appreciated!

Andrew S


  • edited October 2015 Answer ✓
    • Processing's PApplet class by itself can't do much of anything!
    • Only after it's "ignited" by calling main() or runSketch() that a "canvas" is created and the "Animation" Thread starts to call back various events like setup(), draw(), keyPressed(), etc.
    • I see you've got 2 PApplet subclasses above. But I daresay only the 1st has been "ignited".
    • The 2nd subclass attempts to access the "canvas" via textWidth().
    • But since it doesn't have a "canvas" of its own, an NPE is thrown!
    • Either request a PApplet reference from the 1st class...
    • Or place it inside the 1st class as an inner class. Like all ".pde" sketches do anyways! ;;)
    • Either way, 2nd class doesn't need to extend PApplet anymore.
    • That is, it's inheritance by composition/aggregation now. :-\"
  • Yup this is exactly what I needed! Getting some new errors now but looking more into them since they deal with running out of java heap space in eclipse. Thanks a bunch!

Sign In or Register to comment.