control p5: How to access "name" or "text" property in ScrollableList?

edited November 2015 in Library Questions

Hi, I have a simple question about ScrollableLists in controlP5.

I want to acces the "name" or "text" behind the items in a ScrollableLists.

How do I access them, and for instance set a string (in code below named "selected") equal to the value of the item on the list that is selected?

import controlP5.*;
import java.util.*;

ControlP5 cp5;

String selected = "";

void setup() {
  size(400, 400);
  cp5 = new ControlP5(this);
  List l = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h");
  cp5.addScrollableList("dropdown")
     .setPosition(100, 100)
     .setSize(200, 100)
     .setBarHeight(20)
     .setItemHeight(20)
     .addItems(l)
     ;
}

void draw() {
  background(120);
  text("You have selected: " + selected, 100, 300);
}

Answers

  • Answer ✓
    import controlP5.*;
    import java.util.*;
    
    ControlP5 cp5;
    
    String selected = null;
    
    void setup() {
      size(400, 400);
      cp5 = new ControlP5(this);
      List l = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h");
      cp5.addScrollableList("dropdown")
         .setPosition(100, 100)
         .setSize(200, 100)
         .setBarHeight(20)
         .setItemHeight(20)
         .addItems(l)
         ;
    }
    
    void draw() {
      background(120);
      if(selected != null) {
        text("You have selected: " + selected, 100, 300);
      }
    }
    
    //ControlP5 callback - method name must be the same as the string parameter of cp5.addScrollableList()
    void dropdown(int index) {
      selected = cp5.get(ScrollableList.class, "dropdown").getItem(n).get("value");
    }
    

    Alternatively, you could assign the ScrollableList to a variable, in which case the the assignment of selected would be this instead: selected = myDropdownList.getItem(n).get("value");

  • Great, thanks!

    I changed your line 30 to:

    selected = cp5.get(ScrollableList.class, "dropdown").getItem(n).get("name").toString();

    And now it does exactly what I wanted. Thanks a lot :D.

  • can't you store the scrollable list in an object in setup() ?

    that would make the line above shorter and faster

    the cp.get(...) part doesn't change...

Sign In or Register to comment.