ControlP5: How do I tie a slider and a text field together.

Here's my test code so far:

`import controlP5.*;

ControlP5 cp5;

void setup() { size( 700, 500 );

cp5 = new ControlP5( this );

cp5.addSlider( "testSlider" )
.setValue( 80 )
.setSize( 128, 10 )
.setPosition( 50, 100 )
.setRange( 1, 128 )
.setLabel("test slider")
.setScrollSensitivity( .2 )
;

cp5.addTextfield("testField")
 .setValue( 80 )
 .setPosition( 70, 40)
 .setSize( 40,20 )
 .setAutoClear(false)
 .setLabel("rows")
 .setInputFilter(ControlP5.INTEGER);
 ;

}`

I would like to make it so that when I change the slider, the text field changes to that same number, and vice versa. I could setup events for each of the gui elements that upon change, sampled their value, and explicitly set the other one to the same value. But this seems pretty inelegant. Is there a better way to do this?

Tagged:

Answers

  • Hi, like you already suggest in your post, the approach to achieve this kind of behavior is to use events or callbacks for the gui elements, in this case I would use a CallbackListener. A CallbackListener can be added to a controller and then receives events for different actions, in your case a broadcast event should invoke changes.

    so for example for the Slider to change the text of a Textfield you would add a CallbackListener like this (also have a look at the ControlP5callback example)

    .addCallback(new CallbackListener() {
           public void controlEvent(CallbackEvent theEvent) {
             if (theEvent.getAction()==ControlP5.ACTION_BROADCAST) {
               float val = float(((Textfield)theEvent.getController()).getText());
               cp5.get(Slider.class, "testSlider").setValue(val);
             }
           }})
    

    the Slider controller would do the same but change the text of the Textfield with setText() instead of setValue()

    String val = String.format("%.1f", theEvent.getController().getValue());
    cp5.get(Textfield.class, "testField").setText(val);
    

    to trim down the digits after the decimal point you can use String.format, here %.1f takes a float and only uses the first digit after the decimal point.

Sign In or Register to comment.