Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • clearing an ArrayList

    I've around this issue a few times. I have a particle system that contains an ArrayList of particles. I use a separate window for the interface programmed using Control P5.

    usually my particle system lies under a boolean, and that boolean is activated/deactivated by a cp5 toggle. every time i toggle it to false, i want the ArrayList inside the particle system to be cleared, so the particle system starts fresh from zero instead of a simple interruption it's runtime.

    so i put a ps.particles.clear(); in the toggle false condition. everytime it crashes and I get IndexOutOfBoundsException. it also happened to me with a bang and a button.

    what is the most efficient way to really clear an ArrayList?

    here is the code with whats going on.

    main code

    import controlP5.*;
    ControlFrame cf;
    RingSystem r;
    
    boolean isRing = false;
    
    void settings(){
       size(600,600);
    }    
    
    void setup(){
    
         //CONTROLP5
         cf =new ControlFrame(this, 400, displayHeight, "MENU", width, height);
    
         //RING SETUP
         cPos=new PVector(width/2, height/2, 0);
         r=new RingSystem(cPos);
    }
    
    void draw(){
      if (isRing) {
        if (frameCount%30==0) r.addRing();
        r.display();
      }
    }
    

    Ring System

    class RingSystem{
     ArrayList<Ring> rings;
     PVector origin;
     RingSystem(PVector _origin){
       rings=new ArrayList<Ring>();
       origin=_origin.copy();
     }
    
     void addRing(){
      rings.add(new Ring(origin)); 
     }
    
     void display(){
       for(int i=rings.size()-1; i>0; i--){
        Ring r=rings.get(i);
        r.update();
        r.display();
        if(r.isDead()){
         rings.remove(i); 
        }
       }
     }
    }
    

    Ring/Particle

    class Ring {
      PVector origin;
      float dim=0;
      float dimMax=400;
      float life=0;
      float alpha;
    
      Ring(PVector _origin) {
        origin=_origin.copy();
      }
    
      void update() {
        life++;
        //origin.y++;
        //dim=cos(radians(life))*life;
        dim=life;
        alpha=map(life,height*2,0,0,255);
      }
    
      void display() {
        pushMatrix();
        stroke(0, 255, 255,alpha);
        strokeWeight(6);
        noFill();
        translate(origin.x, origin.y, origin.z);
        //rotateX(radians(90));
        ellipse(0, 0, dim, dim);
        popMatrix();
      }
    
      boolean isDead() {
        if (life>height*2) {
          return true;
        } else {
          return false;
        }
      }
    }
    

    Control Frame

    public class ControlFrame extends PApplet {
    
      ControlP5 cp5;
      Object parent;
    
      public void setup() {
        cp5 = new ControlP5(this);  
    
        cp5.addToggle("ringToggle")
          .setPosition(160, 50)
          .setSize(80, 80)
          .setValue(false)
          ;
    }
      void ringToggle(boolean toggle) {
        if (toggle==true) {
          isRing=true;
        } else {
          isRing=false;
    
          r.removeAll(rings);
          for (int i=0; i<r.rings.size(); i++) {
            Ring ri=r.rings.get(i);
            r.rings.remove(i);
          }
        }
      }
    

    }

  • Filepath Issue

    Actually I went back to a previous version of my sketch, applied your new code and it doesn't give me those errors any more... We are REALLY close now...

    The issue now is with font rendering and CP5

    My font code looks like this..

    `    
    
     cp5 = new ControlP5(this); // 
     PFont pfont = createFont("Arial", 24, true);
     ControlFont font = new ControlFont(pfont, 24);`
    

    And the error I get is:

    Inefficient font rendering: use createFont() with a TTF/OTF instead of loadFont().

  • Filepath Issue

    Thanks Kfrajer, I tried the code and got errors while compiling...

    3. ERROR in /private/var/folders/71/whbl6c5x08gczcqq00k33m4w0000gn/T/android317694126990055572sketch/src/processing/test/pixelpetal_v09/pixelpetal_v09.java (at line 354)
        stream =  surface.getAssets().open(filename); //new FileInputStream(filename);//createInput(filename);
                  ^^^^^^^
    surface cannot be resolved
    ----------
    3 problems (1 error, 2 warnings)
    
    BUILD FAILED
    /var/folders/71/whbl6c5x08gczcqq00k33m4w0000gn/T/android317694126990055572sketch/build.xml:15: The following error occurred while executing this line:
    /var/folders/71/whbl6c5x08gczcqq00k33m4w0000gn/T/android317694126990055572sketch/build.xml:28: Compile failed; see the compiler error output for details.
    
    Total time: 1 second
    

    And here is my sketch....

    Any ideas?

    Thanks again.

    Phil

    `
    import com.heroicrobot.dropbit.registry.*;
    import com.heroicrobot.dropbit.devices.pixelpusher.Pixel;
    import com.heroicrobot.dropbit.devices.pixelpusher.Strip;
    import java.util.*;
    import controlP5.*;
    import java.io.*;
    import android.graphics.*;
    
    
    Button myButton1;
    Button myButton2;
    Button myButton3;
    Button myButton4;
    Button myButton5;
    Button myButton6;
    Button myButton7;
    Button myButton8;
    Button myButton9;
    Button myButton10;
    Button myButton11;
    
    
    boolean noStrips = true;
    int buttonYpos = 0;
    
    ControlP5 cp5;
    
    // Set this to true to enable a debug display of the current frame.
    boolean onscreenDebug = true;
    
    int currentFrame = 0;
    
    // setup file path a durations for the image sequences
    
    String[] pathBases = {"null", "black", "grad", "buddah", "wipe", "orange", "embers", "psych", "petals", "sunrise", "smoke", "allseq"};
    int[] durations =     {0,   1,   2000,  1500, 1250, 750, 500, 1000, 1000, 1000, 240,  9704};
    int[] buttonOffsets = {0,   250, 350,   450,  550,  650, 750, 850,  950,  1050, 1150, 1250};
    
    String pathBase = pathBases[1]; // set start patern to "all off"
    int numFrames = durations[1];
    int whichMovie=1;
    
    PImage mainMovie;
    
    
    
    DeviceRegistry registry;
    PusherObserver observer;
    PGraphics offScreenBuffer;
    PImage bg;
    PImage errorScreen;
    PImage loadingScreen;
    
    
    // flags to control whether we redraw the UI
    boolean uiChanged = true;
    
    int Yoffset = -50; // this helps me quickly modify the position of the buttons 
    
    ArrayList<PImage[]> imageSequences;
    
    
    PImage[] loadImageSequence(String basename, int numFrames) {
      // create the array of references
      println("Loading image sequence "+basename+", "+numFrames+" frames.");
      PImage[] imageSequence = new PImage[numFrames];
    
      // now loop over the sequence loading them
      for (int i=0; i<numFrames; i++) {
        String imageName = "sequences/" + basename + "_pixelData/pixelData" + nf(i, 5) + ".png";
        imageSequence[i] = loadImage(imageName);
        println("Image "+imageName+" was loaded as "+imageSequence[i]);
      }
      return imageSequence;
    }
    
    void setup() {
      size(800, 1280, P3D); // Must be first in setup()
    
      // Load all our images.  
    
      imageSequences= new ArrayList<PImage[]>();
      // Add a null object to compensate for the 1-based numbering.
      imageSequences.add(null);
    
      // Load each image sequence and add it to the ArrayList  
      for (int i=1; i<pathBases.length; i++) {
        imageSequences.add(loadImageSequence(pathBases[i], durations[i]));
      }
    
      bg = loadImage("UI_Background.jpg");
      errorScreen = loadImage("noLEDSs.jpg");
      loadingScreen = loadImage("noLEDSs.jpg");
    
      stroke(255);
      noFill();
      strokeWeight(4); 
    
      cp5 = new ControlP5(this); // 
    
      cp5.setAutoDraw(false);
    
      frameRate(24);
    
      // create a new buttons for the UI
    
      myButton1 = cp5.addButton("alloff")
    
        .setCaptionLabel("All Off")
          .setValue(0)
            .setPosition(100, 250+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton2 = cp5.addButton("grad")
    
        .setCaptionLabel("Color Grad")
          .setValue(0)
            .setPosition(100, 350+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton3 = cp5.addButton("buddah")
    
        .setCaptionLabel("Pink Buddah")
          .setValue(0)
            .setPosition(100, 450+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton4 = cp5.addButton("colorwipe")
        .setCaptionLabel("Color Wipe")
          .setValue(0)
            .setPosition(100, 550+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton5 = cp5.addButton("orange")
        .setCaptionLabel("Orange Blossom")
          .setValue(0)
            .setPosition(100, 650+Yoffset)
              .setSize(500, 60)
    
                ;
    
    
    
      myButton6 = cp5.addButton("rustySwirl")
        .setCaptionLabel("Embers")
          .setValue(0)
            .setPosition(100, 750+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton7 = cp5.addButton("psych")
        .setCaptionLabel("psychedelic blue")
          .setValue(0)
            .setPosition(100, 850+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton8 = cp5.addButton("petals")
        .setCaptionLabel("rainbow petals")
          .setValue(0)
            .setPosition(100, 950+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton9 = cp5.addButton("sunrise")
        .setCaptionLabel("Sunrise")
          .setValue(0)
            .setPosition(100, 1050+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton10 = cp5.addButton("smoke")
        .setCaptionLabel("Ice Drops")
          .setValue(0)
            .setPosition(100, 1150+Yoffset)
              .setSize(500, 60)
    
                ;
    
      myButton11 = cp5.addButton("allSeq")
        .setCaptionLabel("All Sequences")
          .setValue(0)
            .setPosition(100, 1250+Yoffset)
              .setSize(500, 60)
    
                ;
    
    
      whichMovie=1; //default
    
      offScreenBuffer = createGraphics(326, 7);// offscreen buffer to hold the pattern
      registry = new DeviceRegistry();
      observer = new PusherObserver();
      registry.addObserver(observer);
      registry.setAntiLog(true);
      registry.setAutoThrottle(true);
    } 
    
    
    
    
    void draw() {
      if (!uiChanged)
        cp5.draw();        // we must do this every frame, or the event handler never fires.
    
      if (uiChanged) {
        buttonYpos = buttonOffsets[whichMovie] + Yoffset;
        background(bg);
        cp5.draw();
        pushMatrix();
        translate(0, buttonYpos);
        rect (100, 0, 500, 60); // selection state for the buttons
        popMatrix();
    
        numFrames = durations[whichMovie];
    
        uiChanged = false;
      }
    
      currentFrame = (currentFrame+1) % numFrames;  // Use % to cycle through frames and loop
      mainMovie = (imageSequences.get(whichMovie))[currentFrame];      // we just reference the images we loaded earlier.
    
      if (noStrips) {
        image(errorScreen, 000, 0, 800, 1280);
        uiChanged = true;
      } // display error if there are no strips detected
    
      if (onscreenDebug)
        image(mainMovie, 0, 0); // blit it so we can see what's happening
      offScreenBuffer.beginDraw();
      offScreenBuffer.image(mainMovie, 0, 0);
      //println(mainMovie);
      scrape(); // scrape the offscreen buffer 
      offScreenBuffer.endDraw();
    
    }
    
    
    
    
    
    // UI selections
    public void controlEvent(ControlEvent theEvent) {
      uiChanged = true;
      println("Took control event.");
      currentFrame = 0;
    }
    
    // ControlP5 automatic event handler methods.
    public void alloff(int theValue) {
      whichMovie = 1;
    }
    
    public void grad(int theValue) {
      whichMovie = 2;
    }
    
    
    
    public void buddah(int theValue) {
      whichMovie = 3;
    }
    
    public void colorwipe(int theValue) {
      whichMovie = 4;
    }
    
    public void orange(int theValue) {
      whichMovie = 5;
    }
    
    public void rustySwirl(int theValue) {
      whichMovie = 6;
    }
    
    public void psych(int theValue) {
      whichMovie = 7;
    }
    
    public void petals (int theValue) {
      whichMovie = 8;
    }
    
    
    public void sunrise(int theValue) {
      whichMovie = 9;
    }
    
    public void smoke(int theValue) {
      whichMovie = 10;
    }
    
    
    public void allSeq(int theValue) {
      whichMovie = 11;
    }
    
    
    void displayLoading() {
    
      loadingScreen = loadImage("noLEDSs.jpg");
      image(loadingScreen, 000, 0, 800, 1280);
    
    }
    
    
    
      public PImage loadImage(String filename) { //, Object params) {
      //    return loadImage(filename, null);
    
      println("Processing CUSTOM loading image....");
    
      InputStream stream=null;
      try {
        stream =  surface.getAssets().open(filename); //new FileInputStream(filename);//createInput(filename);
      }
      //catch(FileNotFoundException e) {}
      catch(IOException e) {}
    
    
      if (stream == null) {
        System.err.println("Could not find the image " + filename + ".");
        return null;
      }
      //    long t = System.currentTimeMillis();
      Bitmap bitmap = null;
      try {
        bitmap = BitmapFactory.decodeStream(stream);
      } 
      finally {
        try {
          stream.close();
          stream = null;
        } 
        catch (IOException e) {
        }
      }
      //    int much = (int) (System.currentTimeMillis() - t);
      //    println("loadImage(" + filename + ") was " + nfc(much));
      if (bitmap == null) {
        System.err.println("Could not load the image because the bitmap was empty.");
        return null;
      } else {
        PImage image = new PImage(bitmap);
        image.parent = this;
        return image;
      }
    }`
    
  • how to show multiple data from arduino

    how to read the value from arduino and then i want to displaying that on processing window. This is my arduino code:

          #include <TimerOne.h>            
          #include <PZEM004T.h>
          #include <LiquidCrystal.h>
    
    
          int dutycycle = 0;     // Initailize duty cylce variable as integer data type
          int incomingByte = 0;
          PZEM004T pzem(2,3);  // (RX,TX) connect to TX,RX of PZEM
          IPAddress ip(192,168,1,1);
          LiquidCrystal lcd(12, 11, 4, 5, 6, 7);
    
    
           void setup()               // Setup function
          {
            Serial.begin(9600);
            pinMode (9, OUTPUT);             // set pin 9 as an output pin for pwm
            pinMode (10, OUTPUT);            // set pin 10 as an output pin for pwm
            Timer1.initialize(20000);             // Initailize timer1 time period as 20 milli second (50 Hz frequency)
            TCCR1A = (TCCR1A & 0x0F) | 0xB0 ;             // set pin 10 inverted of pin 9
            pzem.setAddress(ip);
            lcd.begin(16, 2); // lcd rows and columns
           }
    
    
          void loop()              // loop function starts
          { 
          if (Serial.available() > 0)
          {
          incomingByte = Serial.read ();  
          dutycycle = map(incomingByte, 0, 255, 0, 1023);
          Timer1.pwm(9, dutycycle, 20000);            // Timer1.pwm function takes argument as (pin no. , dutycycle , time period)
          Timer1.pwm(10, 1023-dutycycle, 20000);
    
    
          float v = pzem.voltage(ip);
          if (v < 0.0) v = 0.0;
    
          Serial.print(v);Serial.print("V; ");
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("V= ");
          lcd.setCursor(2,0);
          lcd.print(v);
    
    
          float i = pzem.current(ip);
          if (i < 0.0) i = 0.0;
    
          Serial.print(i);Serial.print("A; ");
          lcd.clear();
          lcd.setCursor(9,0);
          lcd.print("A= ");
          lcd.setCursor(11,0);
          lcd.print(i);
    
    
          float p = pzem.power(ip);
          if (p < 0.0) p = 0.0;
    
          Serial.print(p);Serial.print("W; ");
          lcd.clear();
          lcd.setCursor(9,1);
          lcd.print("W= ");
          lcd.setCursor(11,1);
          lcd.print(p);
    
    
          float e = pzem.energy(ip);
    
          Serial.print("PF= ");Serial.print((p)/(v*i));
          lcd.setCursor(0,1);
          lcd.print("PF=");
          lcd.setCursor(3,1);
          lcd.print((p)/(v*i));
    
          Serial.println(v);
          Serial.println(i);
          Serial.println(p);
          Serial.println((p)/(v*i));
    
         delay(100);  
         }
         }               // loop function ends
    

    i want to send the value of "v","i","p" and "pf" and show it in processing window, this is my processing code :

          import controlP5.*;
          import processing.serial.*;
    
          ControlP5 cP5;
    
          Serial arduino;
          String val= "0";
    
          void setup() 
          {
          size(800, 550);
          println(Serial.list());
          String portName = Serial.list()[0];
          arduino = new Serial(this, portName, 9600);
    
          cP5 = new ControlP5(this);
          cP5.addSlider("ATUR DUTY CYCLE", 0, 255, 0, 210, 155, 350, 50);
          }
    
          void draw() 
          {
          background(#614DED);
          textSize(20);
          fill(#F5ED00);
          text("PENGENDALIAN INVERTER FULL BRIDGE SATU FASA", 140, 30);
          textSize(20);
          text("SECARA WIRELESS BERBASIS ARDUINO", 200,60);
          text("ARUS", 210, 300);
          text("TEGANGAN", 460, 300);
          text("DAYA", 210, 400);
          text("FAKTOR DAYA", 460, 400);
    
          if (arduino.available() >0){
          delay(100);
          val=arduino.readString();}  
    
          textSize(18);
          fill(#FAFF08);
          text(val, 210 ,330 );
    
          textSize(18);
          fill(#FAFF08);
          text(val, 460, 330);
    
          textSize(18);
          fill(#FAFF08);
          text(val, 210, 430);
    
          textSize(18);
          fill(#FAFF08);
          text(val, 460, 430);
    
          }
    
           void controlEvent(ControlEvent theEvent) {
           if(theEvent.isController()) {
    
           int val = int(theEvent.getController().getValue());
           arduino.write(val);
           } 
           }
    

    Thank you very much

  • controlP5 problem.

    I didn't test your code not I attempt running it. First, you should avoid naming your controllers as just numbers. It is not a good practice in short. I also suggest to try shaderWin.cpp5.getController("l").setValue(float(n)); as it seems the first setter was working for you.

    Finally, where are you setting this value? Are you doing it either in setup, draw, any of controlP5 callback functions or any other function that are called inside any of the aforementioned functions? In other words, you are not calling your setter in a global scope, right? I have to ask as this is not clear in your post.

    Kf

  • controlP5 problem.

    hello!

    I`ve a problem with controlP5 library. In a json file i stored the value of a variable of a class name "layer", witch is equal to buttonBar choice.

    buttonBar = layer

    Next, i want to load that value, but i cant make that buttonBar set the value and display on... the same is happening with a listBox.

    but no with sliders: this works perfectly. (t2) is a slider.

          float T2 = shader.getFloat("t2"); // value load from  JSON file
          shaderWin.cpp5.getController("t2").setValue(T2);
    

    but this not:

        int n = numberLayer.getInt("numberLayer");
        shaderWin.cpp5.getController("l").setValue(n); // "l"  is a buttonBar. i want the item number N on.
    
    
    
        cpp5.addButtonBar("l")
          .setPosition(0, 0)
          .setFont(font)
          //.setSize(1000, 20)
          .setWidth(900)
          .setColorBackground(0)
          .addItems(split("0 1 2 3 4 5 6 7 8", " "))
          ;
    
      void l(int n) {
        println("bar clicked, item-value:", n);
        layer.layer = n;
      }
    
    
    anybody know why?
    
  • Send value to a object

    this doesn't make too much sense - at least to me:

    Every Sphere on the screen represent an Obj when i click on that ellipse, i want change with a slider the "total" value for this Obj.

    When you want the ellipses to symbolize your objects, why then additionally put in objects??

    Either ellipses / Spheres OR obj.

    This

    this is really bad:

        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
    
            for (Obj o : obj) {
              o.printt();
              cID = currentSphere.id;
            }
    

    it takes a lot of processor time to check for each sphere ALL objects!!!

    A nested for loop only makes sense when you have a structure like a grid where each line has many cells.

    New version

    New version without obj but with:

    • slider takes the value from clicked ellipse!!!

    Chrisir ;-)

    import controlP5.*;
    
    ArrayList<Sphere> s;
    
    PWindow controller;
    
    int cID=-1;  
    
    // ------------------------------------------------------------
    
    void settings() {
      size(500, 500, P3D);
    }
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
    
      // add one sphere (optional)
      float size1 = 50; 
      Sphere newSphere = new Sphere(
        new PVector(random(size1, width-size1), random(size1, height-size1)), 
        255, 
        size1, 
        0); 
      s.add(newSphere);
    }
    
    void draw() {
      background(0);
    
      for (Sphere ss : s) {   
        ss.display();
        ss.isOver(mouseX, mouseY);
      }
    }
    
    // ------------------------------------------------------------
    // Inputs 
    
    void mousePressed() {
    
      if (mouseButton==RIGHT) { 
        s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
        return; // leave here
      }
    
      //reset 
      cID=-1; 
    
      if (mouseButton==LEFT) {
        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
            currentSphere.isClick = true;
            cID = currentSphere.id;
            float currentSize = s.get(cID).size; 
            controller.cp5.getController("vertices").setValue(currentSize);
          } else {
            currentSphere.isClick = false;
          }
        }//for
      }//if
      //
    } //func 
    
    // ===========================================================
    
    class Sphere {
    
      color c; 
      float size;
      float x, y;
      PVector p = new PVector(0, 0);
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      //constr 
      Sphere(PVector _pos, 
        color _color, 
        float _size, 
        int _id) {
        // 
        p=_pos.copy();
        c = _color;
        size = _size;
        id = _id;
      }//constr
    
      void display() {
        fill(c);
        ellipseMode(RADIUS);
        ellipse(p.x, p.y, 
          size, size);
      }
    
      boolean isOver(float px, float py) {
        float d = dist(px, py, p.x, p.y);
        if (d < size) {
          over = true;
          c = 150;
          if (isClick) 
            c = 25; // color
          return true;
        } else {
          over = false;
          c = 255;
          if (isClick) 
            c = 25; // color
          return false;
        }
      }//func
    }//class
    
    // ===========================================================
    
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50);
      }
    
      void draw() {
        background(0);
    
        if (cID>-1) {
          fill(255);
          stroke(255);
          textSize(13);
          text(cID, width/2, 150);
        }
      }
    
      void vertices(int c) {
    
        if (cID==-1) 
          return; 
    
        Sphere s1 = s.get(cID); 
        s1.size = c;
        println("a slider event. ");
      }
      //
    } //class 
    //
    
  • Send value to a object

    See the reference of controlP5 - could be something like setValue

  • Send value to a object

    Oh, im in a new trouble... In fact this piece of code is a reduction of a bigger program. What i really want is a "interface" to control another object. Now, we change the Sphere.size with a slider. but what i want to change when a Sphere.isclick is the size of another Obj...

    i try this, but it doesnt work. I try others variations without a result. I think you can help appying your cID logic...

    I thinks that is a really easy way.. Every Sphere on the screen represent an Obj when i click on that ellipse, i want change with a slider the "total" value for this Obj.

    (in the real code, the variable "total" represent the detail of a sphere)

    import controlP5.*;
    
    ArrayList<Sphere> s;
    ArrayList<Obj> obj;
    
    PWindow controller;
    int cID=-1;  
    
    void settings() {
      size(500, 500, P3D);
    }
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
      obj = new ArrayList<Obj>();
    
      // add one sphere (optional)
      float size1 = 50; 
      Sphere newSphere = new Sphere(
        new PVector(random(size1, width-size1), random(size1, height-size1)), 
        255, 
        size1, 
        0); 
      s.add(newSphere);
    }
    
    void draw() {
      background(0);
      for (Sphere ss : s) {   
        ss.display();
        ss.isOver(mouseX, mouseY);
      }
    
      println(obj.size());
    }
    
    
    
    void mousePressed() {
      if (mouseButton==RIGHT) { 
        s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
        obj.add(new Obj(int(random(50)), s.size()));
        return; // leave here
      }
    
      //reset 
      cID=-1; 
    
      if (mouseButton==LEFT) {
    
    
    
    
        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
    
            for (Obj o : obj) {
              o.printt();
              cID = currentSphere.id;
            }
    
            currentSphere.isClick = true;
            cID = currentSphere.id;
          } else {
            currentSphere.isClick = false;
          }
        }
      }
    }
    
    // ===========================================================
    
    class Sphere {
    
      color c; 
      float size;
      float x, y;
      PVector p = new PVector(0, 0);
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      Sphere(PVector pos, 
        color _color, 
        float _size, 
        int _id) {
        // 
        p=pos.copy();
        c = _color;
        size = _size;
        id = _id;
      }//constr
    
      void display() {
        fill(c);  
        ellipse(p.x, p.y, 
          size, size);
      }
    
      boolean isOver(float px, float py) {
    
        ellipseMode(RADIUS);
    
        float d = dist(px, py, p.x, p.y);
        if (d < size) {
          over = true;
          c = 150;
          if (isClick) 
            c = 25; // color
          return true;
        } else {
          over = false;
          c = 255;
          if (isClick) 
            c = 25; // color
          return false;
        }
      }//func
    }//class
    
    // ===========================================================
    
    class Obj {
      int total;
      int id;
      Obj(int _total, int _id) {
        total = _total;
        id = _id;
      }
    
      void printt() {
        println(total);
      }
    }
    
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      int vertices = 50;
      float ss;
    
    
      Slider abc;
    
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50)
          ;
      }
    
      void draw() {
        background(0);
    
        if (cID>-1) {
          fill(255);
          stroke(255);
          textSize(13);
          text(cID, width/2, 150);
        }
      }
    
      void vertices(int c) {
    
        if (cID==-1) 
          return; 
    
        Obj o = obj.get(cID); 
        o.total = c;
        println("a slider event. ");
      }
    }//class 
    //
    
  • Send value to a object

    Also, instead of reading the slider throughout, it's better to use slider event

    see

    http://www.sojamo.de/libraries/controlP5/examples/controllers/ControlP5slider/ControlP5slider.pde

    Using size as ID

    here you had

          s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()+1));
    

    (s.size()+1)

    better

     s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
    

    s.size()

    New version

    (lots of other changes too)

    import controlP5.*;
    
    ArrayList<Sphere> s;
    PWindow controller;
    int cID=-1;  
    
    void settings() {
      size(500, 500, P3D);
    }
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
    
      // add one sphere (optional)
      float size1 = 50; 
      Sphere newSphere = new Sphere(
        new PVector(random(size1, width-size1), random(size1, height-size1)), 
        255, 
        size1, 
        0); 
      s.add(newSphere);
    }
    
    void draw() {
      background(0);
      for (Sphere s : s) {
        s.display();
        s.isOver(mouseX, mouseY);
      }
    }
    
    //void select() {
    //  for (Sphere currentSphere : s) {
    //    if (currentSphere.isClick) {
    //      // println(currentSphere.id, "HOLA");
    //      currentSphere.c = 25; // color
    //      // println("");
    //    }
    //  }
    //}
    
    void mousePressed() {
      if (mouseButton==RIGHT) { 
        s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
        return; // leave here
      }
    
      //reset 
      cID=-1; 
    
      if (mouseButton==LEFT) {
        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
            currentSphere.isClick = true;
            cID = currentSphere.id;
          } else {
            currentSphere.isClick = false;
          }
        }
      }
    }
    
    // ===========================================================
    
    class Sphere {
    
      color c; 
      float size;
      float x, y;
      PVector p = new PVector(0, 0);
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      Sphere(PVector pos, 
        color _color, 
        float _size, 
        int _id) {
        // 
        p=pos.copy();
        c = _color;
        size = _size;
        id = _id;
      }//constr
    
      void display() {
        fill(c);  
        ellipse(p.x, p.y, 
          size, size);
      }
    
      boolean isOver(float px, float py) {
    
        ellipseMode(RADIUS);
    
        float d = dist(px, py, p.x, p.y);
        if (d < size) {
          over = true;
          c = 150;
          if (isClick) 
            c = 25; // color
          return true;
        } else {
          over = false;
          c = 255;
          if (isClick) 
            c = 25; // color
          return false;
        }
      }//func
    }//class
    
    // ===========================================================
    
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      int vertices = 50;
      float ss;
    
    
      Slider abc;
    
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50)
          ;
      }
    
      void draw() {
        background(0);
    
        if (cID>-1) {
          fill(255);
          stroke(255);
          textSize(13);
          text(cID, width/2, 150);
        }
      }
    
      void vertices(float c) {
    
        if (cID==-1) 
          return; 
    
        Sphere obj = s.get(cID); 
        obj.size = c;
        println("a slider event. ");
      }
    }//class 
    //
    
  • Send value to a object

    Hello everybody. I`ve a problem:

    I`ve a array of ellipse Objects. Every object has his variable of size in the constructor. In a second screen, via controlP5, a slider that change the size of every ellipse. What i want is change the size of an ellipse object when isClicked is true, and in that particular object, and store that value. But i cant, and i dont know exaclty why. I think that when i change the size in the constructor every object take the same value.

    here the code, sorry for my very bad english, hope you understand:

    (in resume: click the object, change it value, store the value. click in another object, and change it value (different of object 1)…etc.)

    import controlP5.*;
    
    ArrayList<Sphere>s;
    PWindow controller;
    
    
    void settings() {
      size(500, 500, P3D);
    }
    
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
      s.add(new Sphere(new PVector(random(width), random(height)), 255, 50, 0));
    }
    
    void draw() {
      background(0);
      pushMatrix();
      select();
    
      for (Sphere s : s) {
        s.display();
        s.isOver(mouseX, mouseY);
      }
      popMatrix();
    }
    
    void select() {
      for (Sphere s : s) {
        if (s.isClick) {
          println(s.id, "HOLA");
          s.c = 25;
          println("");
        }
      }
    }
    
    void mousePressed() {
    
      if (mouseButton==RIGHT) s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()+1));
    
      for (Sphere s : s) {
        if (mouseButton==LEFT && s.over) {
          s.isClick = true;
        } else {
          s.isClick = false;
        }
      }
    }
    
    class Sphere {
    
      float c, size;
      float x, y;
      ArrayList<PVector> p = new ArrayList<PVector>();
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      Sphere(PVector pos, float _color, float _size, int _id) {
        p.add(pos);
        c = _color;
        size = _size;
        id = _id;
      }
    
      void display() {
        for (PVector pos : p) {
          pushMatrix();
          translate(pos.x, pos.y);
          fill(c);  
          ellipse(0, 0, size, size);
          popMatrix();
        }
      }
    
      boolean isOver(float px, float py) {
        ellipseMode(RADIUS);
        for (PVector pos : p) {
          float d = dist(px, py, pos.x, pos.y);
          if (d < size) {
            over = true;
            c = 150;
            return true;
          } else {
            over = false;
            c = 255;
            return false;
          }
        }
        return false;
      }
    }
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      int vertices = 50;
      float ss;
    
    
      Slider abc;
    
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50)
          ;
      }
    
      void draw() {
        background(0);
    
        for (int i = s.size()-1; i >= 0; i--) {
          Sphere obj = s.get(i); 
          ss = vertices;
    
          if (obj.isClick==true) {
            fill(255);
            stroke(255);
            textSize(13);
            text(i, width/2, 150);
            println(i);
            obj.size = vertices;
          }
        }
      }
    
    }
    
  • Send individual msj to a shader

    hey everybody. this time i've a problem sending invididual mensajes to a fragment shader. I've an array of spheres, and i want that every sphere have a different size of blur, witch is a uniform of the fragment. The main code is from an example, a post-processing effects.

    How can i do?

    import controlP5.*;
    
    ControlP5 cp5;
    import peasy.*;
    
    ArrayList<Sphere>s;
    
    PGraphics canvas;
    
    PGraphics brightPass;
    PGraphics horizontalBlurPass;
    PGraphics verticalBlurPass;
    
    PShader bloomFilter;
    PShader blurFilter;
    PeasyCam cam;
    float angle = 0;
    
    final int surfaceWidth = 250;
    final int surfaceHeight = 250;
    
    float luminanceFilter = 0.02;
    float blurSize = 100;
    float sigma = 200;
    
    void setup()
    {
      cam = new PeasyCam(this, 1400);
      size(1000, 1000, P3D);
    
      s = new ArrayList<Sphere>();
    
      canvas = createGraphics(width, height, P3D);
    
      brightPass = createGraphics(width, height, P2D);
      brightPass.noSmooth();
    
      horizontalBlurPass = createGraphics(width, height, P2D);
      horizontalBlurPass.noSmooth(); 
    
      verticalBlurPass = createGraphics(width, height, P2D);
      verticalBlurPass.noSmooth(); 
    
      bloomFilter = loadShader("bloomFrag.glsl");
      blurFilter = loadShader("blurFrag.glsl");
    }
    
    void draw()
    {
      background(0);
      bloomFilter.set("brightPassThreshold", luminanceFilter);
      angle += 0.05;
    
      for(Sphere s: s){
      blurFilter.set("blurSize", s.p);
      }
    
      blurFilter.set("sigma", sigma); 
    
      canvas.beginDraw();
      render(canvas);
      canvas.endDraw();
    
      // bright pass
      brightPass.beginDraw();
      brightPass.shader(bloomFilter);
      brightPass.image(canvas, 0, 0);
      brightPass.endDraw();
    
      // blur horizontal pass
      horizontalBlurPass.beginDraw();
      blurFilter.set("horizontalPass", 1);
      horizontalBlurPass.shader(blurFilter);
      horizontalBlurPass.image(brightPass, 0, 0);
      horizontalBlurPass.endDraw();
    
      // blur vertical pass
      verticalBlurPass.beginDraw();
      blurFilter.set("horizontalPass", 0);
      verticalBlurPass.shader(blurFilter);
      verticalBlurPass.image(horizontalBlurPass, 0, 0);
      verticalBlurPass.endDraw();
    
    
      cam.beginHUD();
      blendMode(BLEND);
      blendMode(SCREEN);
      image(brightPass, 0, 0);
      image(verticalBlurPass, 0, 0);
    
      cam.endHUD();
    
    println(frameRate);
    }
    
    void render(PGraphics pg)
    {
      cam.getState().apply(pg);
    
      pg.background(0, 50);
    
      canvas.pushMatrix();
      canvas.translate(width/2, height/2);
      for(Sphere s: s){
      s.display();
    
      }
      canvas.popMatrix();
    
    
    }
    
    void mousePressed() {
      s.add(new Sphere(random(-width/2, width/2), random(-height/2, height/2), random(1000)));
    }
    
    
    class Sphere {
    
      float p;
      float w;
      float h;
    
      Sphere(float _w, float _h, float _p) {
      p = _p;
      w = _w;
      h = _h;
      }
    
      void display() {
        canvas.pushMatrix();
        canvas.translate(w, h);
        noFill();
        canvas.sphere(100);
    
        canvas.popMatrix();
      }
    }
    
  • CSV file not found in android but no problem in processing 3

    Here's the code for my sketch that I added to the processing android demo. The problem starts with the ObserverElement. It seems to be trying to read another file using Reader.java

    I think I see why its not working with the demo. The difference is that the demo uses gradle and my sketch that worked was jammed into a project(the clearsky android example) imported from eclipse. Theres some kind of dependency issue maybe.

    package in.omerjerk.processingdemo.sketch;
    
    import java.util.Arrays;
    import java.util.List;
    
    import controlP5.ControlP5;
    import controlP5.DropdownList;
    import controlP5.ScrollableList;
    import controlP5.Textarea;
    import jparsec.ephem.Ephem;
    import jparsec.ephem.EphemerisElement;
    import jparsec.ephem.EphemerisElement.COORDINATES_TYPE;
    import jparsec.ephem.EphemerisElement.FRAME;
    import jparsec.ephem.Functions;
    import jparsec.ephem.Nutation;
    import jparsec.ephem.Target.TARGET;
    import jparsec.ephem.planets.EphemElement;
    import jparsec.ephem.stars.StarElement;
    import jparsec.ephem.stars.StarEphem;
    import jparsec.ephem.stars.StarEphemElement;
    import jparsec.io.ConsoleReport;
    import jparsec.math.Constant;
    import jparsec.observer.LocationElement;
    import jparsec.observer.ObserverElement;
    import jparsec.time.AstroDate;
    import jparsec.time.SiderealTime;
    import jparsec.time.TimeElement;
    import jparsec.time.TimeElement.SCALE;
    import jparsec.time.TimeScale;
    import processing.core.PApplet;
    import processing.core.PFont;
    
    //import jparsec.ephem.IAU2006;
    //import jparsec.ephem.IAU2006.CIO_EPHEMERIS;
    //import jparsec.ephem.planets.JPLEphemeris;
    //import jparsec.math.matrix.Matrix;
    //import jparsec.observer.EarthOrientationParameters;
    
    public class CSVTest2 extends PApplet {
    
    
    
    
    //import java.sql.*;
    //import de.bezier.data.sql.*;
    
    //import java.lang.*;
    
    //import java.time.*;
    
    //SQLite db;
    ControlP5 cp5;
    ControlP5 controlP5;
    Textarea myTextarea;
    
    int Latitude_1 = 39;
    int Lat_minutes = 20;
    int Lat_seconds = 10;
    int Longitude_1 = -77;
    int Lon_minutes = 00;
    int Lon_seconds = 26;
    float Lon = 0;
    float Lat = 0;
    
    //ScrollableList Name1;
        DropdownList Name1;
    ScrollableList Name2;
    String Star1 = " ";
    String Star2 = " ";
    
    String starName = " ";
    float ra = 0;
        String proper = " ";
    float RA = 0;
    float dec = 0;
    double pmra = 0;
    double pmdec = 0;
    double rv = 0;
        int i = 0 ;
    PFont f;
    int z = 18;
        int index = 3;
        int timer;
        int wait = 10000;
    
    
    
    
    public void setup()
    {
     //  size( 100, 100 );
    
    
     f = createFont("Arial",16,true); 
    //  db = new SQLite( this, "hygdata.db" );  // open database file
    
      cp5 = new ControlP5(this);
      controlP5 = new ControlP5(this);
                   List l = Arrays.asList("Procyon","Rasalhague","Dubhe", "Mirphak", "Alkaid","Altair", "Alioth", "Spica", "Betelgeuse", "Capella", "Vega","Polaris", "Menkalinan", "Pollux", "Regulus","Deneb", "Denebola");
      /* add a ScrollableList, by default it behaves like a DropdownList */
    //  Name1 = cp5.addScrollableList("StarName  1")
        Name1 = cp5.addDropdownList("StarName  1")
         .setPosition(20, 270)
         .setSize(300, 200)
         .setBarHeight(50)
         .setItemHeight(50)
         .addItems(l)
         // .setType(ScrollableList.LIST) // currently supported DROPDOWN and LIST
         ;
    
    
         controlP5.addSlider("Latitude_1",0,90,Latitude_1,20,10,255,30);
         controlP5.addSlider("Lat_minutes",0,60,Lat_minutes,20,50,255,30);
         controlP5.addSlider("Lat_seconds",0,60,Lat_seconds,20,90,255,30);
    
         controlP5.addSlider("Longitude_1",-180,180,Longitude_1,20,130,255,30);
         controlP5.addSlider("Lon_minutes",0,60,Lon_minutes,20,170,255,30);
         controlP5.addSlider("Lon_seconds",0,60,Lon_seconds,20,210,255,30);
    
    
           Name2 = cp5.addScrollableList("StarName  2")
         .setPosition(20, 590)
         .setSize(300, 200)
         .setBarHeight(50)
         .setItemHeight(50)
         .addItems(l)
        ; 
    
    
    
    
    
        myTextarea = cp5.addTextarea("txt")
                      .setPosition(420,10)
                      .setSize(950, 720)
                      .setFont(createFont("arial", 20))
                      .setLineHeight(20)
                      .setColor(color(255))
                      .setColorBackground(color(255, 0))
                      .setColorForeground(color(255, 100));
    
        timer = millis();//store the current time
    
    
    }
    
    public void draw() {
     background(0, 0, 0);
        String[] starLines = loadStrings("stardata.csv");
        println("Loaded " + starLines.length + " stars:");
    
        Lat = (float)Latitude_1 + (float)Lat_minutes/60 + (float)Lat_seconds/3600;  //Estimated Latitude
        Lon = (float)Longitude_1 - (float)Lon_minutes/60 - (float)Lon_seconds/3600; //Estimated Longitude
    
       if (Longitude_1 > 0) {
       Lon = (float)Longitude_1 + (float)Lon_minutes/60 + (float)Lon_seconds/3600; //East of Greenwich
       }
    
        for ( i = 0 ; i < starLines.length; i++) {
    
            String[] stars = splitTokens(starLines[i], ", ");
            String proper = (stars[0]);
            String con = (stars[1]);
            double dec = PApplet.parseFloat(stars[2]);
            double ra = PApplet.parseFloat(stars[3]);
            double pmra = PApplet.parseFloat(stars[4]);
            double pmdec = PApplet.parseFloat(stars[5]);
            double rv = PApplet.parseFloat(stars[6]);
    
            ra = ra * 15;
    
            Star1 = Name1.getCaptionLabel().getText();
            if (Star1 == "Procyon") {
                z = 47;
            }
            if (Star1 == "Rasalhague") {
                z = 93;
            }
            if (Star1 == "Dubhe") {
                z = 57;
            }
            if (Star1 == "Mirphak") {
                z = 18;
            }
            if (Star1 == "Alkaid") {
                z = 73;
            }
    
    
            for (int j = 1; j < i; j = i+1) {
    
                try {
    
    
                        if (i == z) {   //14 = Polaris 69 = Dubhe
                            //  AstroDate astro = new AstroDate(2008, 4, 24, 10, 36, 18);
                            AstroDate astro = new AstroDate();
                            //  System.out.println(astro);
                            TimeElement time = new TimeElement(astro, SCALE.UNIVERSAL_TIME_UTC);
                            ObserverElement obs = new ObserverElement("", Lon * Constant.DEG_TO_RAD, Lat * Constant.DEG_TO_RAD, 88, 0);
                            ObserverElement obs0 = obs.clone();
                            EphemerisElement eph = new EphemerisElement(TARGET.Moon, COORDINATES_TYPE.APPARENT, EphemerisElement.EQUINOX_OF_DATE, EphemerisElement.GEOCENTRIC, EphemerisElement.REDUCTION_METHOD.IAU_2009,
                                    FRAME.DYNAMICAL_EQUINOX_J2000, EphemerisElement.ALGORITHM.MOSHIER); //EphemerisElement.ALGORITHM.MOSHIER); //EphemerisElement.ALGORITHM.JPL_DE405); //.ALGORITHM.JPL_DE405);
    
                            eph.correctForPolarMotion = false;   //originally false
                            eph.correctEOPForDiurnalSubdiurnalTides = false;  //originally false
                            eph.correctForEOP = true;  //originally false
                            //    EarthOrientationParameters.clearEOP();
                            Nutation.clearPreviousCalculation();
    
    
                            //    System.out.println("Geodetic location: "+Functions.formatAngleAsDegrees(obs.getLongitudeRad(), 3) + " / "+Functions.formatAngleAsDegrees(obs.getLatitudeRad(), 3) + " / "+obs.getHeight());
                            double TTminusUT1 = TimeScale.getTTminusUT1(time, obs);
                            // Force TT-UT1 as in the example
                            TTminusUT1 = 65.571845f;
                            TimeScale.forceTTminusUT1(time, obs, TTminusUT1);
                            // Force EOP parameters as in the example
                            double UT1minusUTC = -0.387845f, x = -0.002f, y = 0.529f, dx = 0, dy = 0;
                            boolean dxdyAredPsidEpsilon = false;
                            double jd_UTC = TimeScale.getJD(time, obs, eph, SCALE.UNIVERSAL_TIME_UTC);
                            //     EarthOrientationParameters.forceEOP(jd_UTC, eph, UT1minusUTC, x, y, dx, dy, dxdyAredPsidEpsilon);
    
                            double jd_TT = TimeScale.getJD(time, obs, eph, SCALE.TERRESTRIAL_TIME);
                            double jd_UT1 = TimeScale.getJD(time, obs, eph, SCALE.UNIVERSAL_TIME_UT1);
    
                            StarElement star = new StarElement(proper, (double) ra * Constant.DEG_TO_RAD, (double) dec * Constant.DEG_TO_RAD,
                                    0, 0, (float) (pmra * Constant.ARCSEC_TO_RAD / Math.cos((double) dec * Constant.DEG_TO_RAD)),
                                    (float) (pmdec * Constant.ARCSEC_TO_RAD), (float) rv, Constant.J2000, FRAME.ICRF);
                            //  System.out.println("Angular Velocity:  " + pmra);
                            StarEphemElement ephem = StarEphem.starEphemeris(time, obs, eph, star, false);
    
                            eph.isTopocentric = true;
                            ephem = StarEphem.starEphemeris(time, obs, eph, star, false);
                            //   double last = SiderealTime.greenwichMeanSiderealTime(time, obs, eph);
                            double last = SiderealTime.apparentSiderealTime(time, obs, eph);
                            // SiderealTime.
                            eph.correctForPolarMotion = false;  //was true
                            eph.correctEOPForDiurnalSubdiurnalTides = false; //was true
                            eph.correctForEOP = false; //was true
                            Nutation.clearPreviousCalculation();
                            ephem = StarEphem.starEphemeris(time, obs, eph, star, false);
                            // ephem = IAU2006.getStarEphemerisWithRespectCIO(time, obs, eph, star, CIO_EPHEMERIS.topocentric);
    
                            LocationElement loc = ephem.getEquatorialLocation();
    
                            System.out.println(loc);
    
    
                            boolean full_ephem = true;
                            EphemElement sephem = Ephem.getEphemeris(time, obs, eph, true);
                            // ConsoleReport.fullEphemReportToConsole(sephem);
                            String Results = ConsoleReport.getBasicEphemReport(sephem, false);
    
    
    
                            myTextarea.setText(("Geodetic location: " + Functions.formatAngleAsDegrees(obs.getLongitudeRad(), 3) + " / " + Functions.formatAngleAsDegrees(obs.getLatitudeRad(), 3) + " / " + obs.getHeight()) +
                                            "\n" + ("JD TT: " + jd_TT + "\n" + "UT1: " + jd_UT1 + "\n" + "TT-UT1: " + TTminusUT1) + "\n" +
                                            (proper + "  geocentric") + "\n" +
                                            ("RA:  " + Functions.formatValue(ephem.rightAscension * Constant.RAD_TO_DEG / 15.0f, 10)) + "\n" +
                                            ("RA:  " + Functions.formatRA(ephem.rightAscension, 4)) + "\n" +
                                            ("DEC: " + Functions.formatAngleAsDegrees(ephem.declination, 10)) + "\n" +
                                            ("DEC: " + Functions.formatDEC(ephem.declination, 4)) + "\n" + ("GP:  " + loc) + "\n" +
                                            ("Az:  " + Functions.formatValue(ephem.azimuth * Constant.RAD_TO_DEG, 10)) + "\n" +
                                            ("Az:  " + Functions.formatAngle(ephem.azimuth, 4)) + "\n" +
                                            ("Alt:  " + Functions.formatValue(ephem.elevation * Constant.RAD_TO_DEG, 10)) + "\n" +
                                            ("Alt:  " + Functions.formatDEC(ephem.elevation)) + "\n" + "\n" +
                                            //("Local Apparent Sidereal Time::  " + ( ((last)* Constant.RAD_TO_HOUR)+ 4)+"\n"+
                                            ("Local Apparent Sidereal Time::  " + (Functions.formatRA((last))) + "\n" + "\n" +
                                                    //  (Functions.formatRA ((last)))
                                                    ("Basic Ephemeris Report:  " + Results))
                                    //  ("Basic Ephem Report:  "))
                            );
                        }
                    }catch(Exception exc){
                        exc.printStackTrace();
                    }
    
                }
    
    
          //  }
        }
    
    
    
    
    }
    
    
    
    
      public void settings() {  size(1000, 750); }
      static public void main(String[] passedArgs) {
        String[] appletArgs = new String[] { "CSVTest2" };
        if (passedArgs != null) {
          PApplet.main(concat(appletArgs, passedArgs));
        } else {
          PApplet.main(appletArgs);
        }
      }
    }
    
  • Stacktrace Question - StringIndexOutOfBoundsException

    I take that to mean you are not using the Println class from controlP5.

    Are you calling displayln(String txt) from a secondary thread?

  • Stacktrace Question - StringIndexOutOfBoundsException

    I am using a function that I wrote to update the text area:

    void displayln(String txt)
    {
      println(txt);
      s += (txt + "\n");
      if (s.length() > 2000)
      {
        s = s.substring(1000);
      }
      Output.setText(s);
    }
    

    If I comment out everything except the println(txt) line the exception never happens. I have also verified that it isn't the call to substring in my function that generates the exception. Here is the exception I get:

    java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at java.lang.String.substring(String.java:1967)
        at controlP5.ControlFont.calculateHeight(Unknown Source)
        at controlP5.ControlFont.adjust(Unknown Source)
        at controlP5.Label$MultilineLabel.draw(Unknown Source)
        at controlP5.Label.draw(Unknown Source)
        at controlP5.ControllerGroup.draw(Unknown Source)
        at controlP5.ControllerGroup.drawControllers(Unknown Source)
        at controlP5.ControllerGroup.draw(Unknown Source)
        at controlP5.ControlWindow.draw(Unknown Source)
        at controlP5.ControlWindow.draw(Unknown Source)
        at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at processing.core.PApplet$RegisteredMethods.handle(PApplet.java:1427)
        at processing.core.PApplet$RegisteredMethods.handle(PApplet.java:1420)
        at processing.core.PApplet.handleMethods(PApplet.java:1614)
        at processing.core.PApplet.handleDraw(PApplet.java:2450)
        at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1557)
        at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
    

    I also tried using the technique in the console example instead of my displayln function and I get the same exception.

  • Stacktrace Question - StringIndexOutOfBoundsException

    I have looked at the controlP5 source code and can confirm there is a possible bug in the ControlFont class, the calculateHeight(...) method.

    Theoretically this method can throw a StringIndexOutOfBoundsException under certain circumstances but looking at the source code it is difficult to see how these circumstances might arise.

    Are you using controlP5'sPrintln class in your program?

  • Stacktrace Question - StringIndexOutOfBoundsException

    My mistake it looks like a bug in controlP5. I should have looked at the stacktrace more closely.

  • Stacktrace Question - StringIndexOutOfBoundsException

    @quark looks like this is a bug in controlP5. I found the following on the GitHub issues page for the project:

    https://github.com/sojamo/controlp5/issues/9

    I also modified the example as follows and was able to determine that the exception is thrown on draw(). What's strange is that it doesn't always happen right away after setMax is set. On one try I made it through draw() 21 times before the exception was thrown. Sometimes it is thrown the first time through.

    import controlP5.*;
    
    ControlP5 cp5;
    
    Textarea myTextarea;
    
    int c = 0;
    boolean case3 = false;
    int count = 0;
    
    Println console;
    
    void setup() {
      size(700, 400);
      cp5 = new ControlP5(this);
      cp5.enableShortcuts();
      frameRate(50);
      myTextarea = cp5.addTextarea("txt")
                      .setPosition(100, 100)
                      .setSize(200, 200)
                      .setFont(createFont("", 10))
                      .setLineHeight(14)
                      .setColor(color(200))
                      .setColorBackground(color(0, 100))
                      .setColorForeground(color(255, 100));
      ;
    
      console = cp5.addConsole(myTextarea);//
    }
    
    
    void draw() {
      println("Point 1");
      if (case3)
      {
        count += 1;
        println("Made it to loop #: " + count);
      }
      println("Point 2");
      background(128);
      noStroke();
      ellipseMode(CENTER);
      float n = sin(frameCount*0.01)*300;
      fill(110, 255,220);  
      ellipse(width/2, height/2, n , n);
    
      println(frameCount+"\t"+String.format("%.2f", frameRate)+"\t"+String.format("%.2f", n));
      println("Point 3");
    }
    
    void keyPressed() {
      switch(key) {
        case('1'):
        console.pause();
        break;
        case('2'):
        console.play();
        break;
        case('3'):
        console.setMax(8);
        case3 = true;
        break;
        case('4'):
        console.setMax(-1);
        break;
        case('5'):
        console.clear();
        break;
      }
    }
    

    The exception and behavior are consistent with what I am seeing in my project...although I'm not using the setMax() method.

  • Stacktrace Question - StringIndexOutOfBoundsException

    The controlP5 console example worked perfectly for me. It is extremely unlikely that the problem is due to a bug in controlP5 because it is a very popular libray used by thousands and someone is likely to have experienced it before.

    In the method displayln(...) is the variable s being shared by both threads?

    If it is then that could be your problem - s is being changed between testing its length and calling substring(...)