Is textWidth() misbehaving itself or am I missing something?

edited November 2013 in Questions about Code

I reduced some of my code to this:

Menu m = new Menu();

void setup() {
  size(100, 100);
}

void draw() {
}

class Menu {
  float foo;
  Menu() {
    foo = textWidth("Foo");
  }
}

It throws an error about "java.lang.NullPointerException". Looking at the reference it does not seem I am doing anything wrong that I can see: http://processing.org/reference/textWidth_.html

Answers

  • Menu m;
    
    void setup() {
      size(100, 100);
    
      m = new Menu();
    
    }
    
    void draw() {
    }
    
    class Menu {
      float foo;
      Menu() {
        foo = textWidth("Foo");
      }
    }
    

    This worked for me. It could be that textWidth needs the size() function to have been run? I have found it is not a good idea to initialize non-primitive variables outside of the setup() function.

  • Thank you, would have never occurred to me

  • Good catch, billautomata. Indeed, before setup() is run, I think the default font isn't initialized, so it cannot be used to compute the text width. Another case to add to "beware of complex initializations in global declarations" (the classical case being using loadXxx() there).

Sign In or Register to comment.