controlP5: Slider linked to int variable doesn't show (some) values

edited February 2014 in Library Questions

I ran into a problem with a slider whose value is set by the program. In the example the initial value of 51 doesn't show up, instead 50 will be shown. The same is true for other values, but not for all. At these missing values, incrementing also doesn't work (but decrementing does). On the other hand, by dragging the slider manually these values can be reached. Any ideas? I am working with controlP5 2.0.4 with Processing 2.1.1 on Mac OSX 10.9.1

import controlP5.*;

ControlP5 cp5;
Slider sl;
int val;

void setup() {
  val = 51;
  size(600,400);
  cp5 = new ControlP5(this);
  sl = cp5.addSlider("val",1,100,100,200,400,20);
  sl.setAutoUpdate(true);
}

void draw() {
}

void keyPressed() {
  if (key == '+') {
    val+=1;
  }
  if (key == '-') {
    val-=1;
  }
}
Tagged:

Answers

  • Hi, these are rounding errors, if you change the type of val from int to float you can see that some values appear as expected and some are off by a fraction of 0.01. to quickly solve this for now, see code below:

    import controlP5.*;
    
    ControlP5 cp5;
    Slider sl;
        float val; // change type from float to int
    
    void setup() {
    
      size(600, 400);
      cp5 = new ControlP5(this);
      sl = cp5.addSlider("val", 1, 100, 100, 200, 400, 20);
      sl.setAutoUpdate(true);
    
      // add a callback listener to adjust the value-label of the slider
      // for each value change.
      CallbackListener adjustLabel = new CallbackListener() {
        public void controlEvent(CallbackEvent c) {
          if(c.getAction()==ControlP5.ACTION_BROADCAST) {
            sl.getValueLabel().setText(String.format("%.0f" , sl.getValue()));
          }
        }
      };
      // add the callback listener to slider sl 
      sl.addCallback(adjustLabel);
    
      val = 51;
    }
    
    void draw() {
      // since val is of type float now, you need to convert it to
      // an int - here you can choose from int(), round(), ceil() or floor()
      // round() 'Calculates the closest int value that is less than or equal 
      // to the value of the parameter'.
      println(round(val));
    }
    
    void keyPressed() {
      if (key == '=') {
        val+=1;
      }
      if (key == '-') {
        val-=1;
      }
    }
    
  • Hi sojamo, thank you for the answer, which works well. But I am not sure if the question is answered. In order to avoid callback listeners and setting the value manually by formatting and rounding, I thought I could use linked integers. So, is the int behavior a bug or a feature?
    Best, Wolfgang

Sign In or Register to comment.