How come a "pre-defined" function cant be put inside of a class?

edited July 2015 in How To...

I tried putting void mousePressed inside of a class and it wouldn't work, but then when I moved it outside of the class it worked. How come it only worked when outside of the class?

Answers

  • edited July 2015

    mousePressed() is a Processing PApplet's callback function. Just like setup() & draw() are too.
    If we place any of them inside another class, the PApplet class won't be able to find them!
    Unless we registerMethod() them btW: :P
    http://forum.Processing.org/two/discussions/tagged?Tag=registermethod()

  • edited July 2015

    Place mousePressed() in the global scope and have it call your class' method

    Here is an example:

    Foo[] foo;
    int counter = 0;
    
    void setup() {
      size(100, 100);
      foo = new Foo[3];
      for (int i = 0; i < 3; i++)
        foo[i] = new Foo(i);
    }
    
    void draw() {
    }
    
    void mousePressed() {
      foo[counter].sayHello();
      counter = (counter + 1) % 3;
    }
    
    class Foo {
      int index;
    
      Foo(int index) {
        this.index = index;
      }
    
      void sayHello() {
        println("Hello from: " + index);
      }
    }
    
  • edited July 2015

    mousePressed is a build-in function that can obly be seen by processing when it's outside the classes. So when it's on a global level.

    As been said you can call the hidden mousePressed (it can have any name) that's inside the class from the real in-build mousePressed (outside the class):

    void mousePressed(){ 
    
          myObject.mousePressed();
    

    Same goes for mouseClicked etc etc

Sign In or Register to comment.