Referencing to mainApp(PApplet) instead of "this"

edited July 2017 in Library Questions

Hi, I would like to use the gif library out of a class that I have written. If I write something like:
Gif myAnimation = new Gif(this, myFile);
...Processing gives an error as it references to my class and not my main App. How do I reference to main sketch? I am pretty sure it has something to do with PApplet, but I can not get it working! Thank you!

Answers

  • pass the papplet into your class via the constructor... use that in the Gif constructor call.

    see the Processing in Eclipse with Multiple Classes bit of this:

    https://processing.org/tutorials/eclipse/

  • edited July 2017

    Hi koogs! Thank you! I really have to learn how classes work in processing! Just as a fast workaround that I am sure is not the best way I just found this in another threat "sketchname".this. I shouldn't change the name of my sketch now, right!? :)

  • edited July 2017 Answer ✓

    Java's keyword this is always of the datatype of the class block it was typed in.
    Let's say your class is called MyGif:

    import gifAnimation.Gif;
    
    class MyGif {
      Gif myAnimation;
    
      MyGif(String myFile) {
        myAnimation = new Gif(this, myFile);
      }
    }
    

    That won't compile b/c Gif's constructor demands that its 1st parameter to be of datatype PApplet.
    But that this is of datatype MyGif instead. #-o

    There are many approaches to workaround it. And you've already found out 1 as SketchName.this. :ar!

    But the simplest 1 is to instantiate such libraries in the main sketch; and then pass it as an argument for the target class: *-:)

    /** 
     * MyGifAnim (v1.0)
     * GoToLoop (2017/Jul/14)
     *
     * Forum.Processing.org/two/discussion/23440/
     * referencing-to-mainapp-papplet-instead-of-this#Item_3
     */
    
    import gifAnimation.Gif;
    
    MyGif gif;
    
    void setup() {
      smooth(3);
      frameRate(60);
      imageMode(CENTER);
    
      gif = new MyGif(new Gif(this, "anim.gif"));
      getSurface().setSize(gif.myAnimation.width, gif.myAnimation.height);
    }
    
    void draw() {
      background(-1);
      image(gif.myAnimation, width>>1, height>>1);
    }
    
    class MyGif {
      Gif myAnimation;
    
      MyGif(Gif gif) {
        myAnimation = gif;
        gif.loop();
      }
    }
    
Sign In or Register to comment.