I want to get the value of a cp5 DropdownList

I am trying to select a folder from a cp5 Dropdown List, but nothing I do seems to work. My best attempt is

(The current data folder contains three folders, “A”, “B”, and “C”, which are read perfectly well on the DropdownList)

import controlP5.*;
ControlP5 cp5;
import java.io.File;

float folder = 0.0;

String[] names;
int index = 0;

void setup() {
  size(500,500);
  cp5 = new ControlP5(this);
  File dir = new File(dataPath(""));
  names = dir.list();
  DropdownList droplist = cp5.addDropdownList("Sets")
  .setPosition(width/2 - 100, height/3 - 50)
  .setSize(200,120)
  .setBarHeight(40)
  .setItemHeight(40)
  .setOpen(false);
  for (int i=0; i < names.length; i++) {
    droplist.addItem(names[i], i);
  }
}

void draw() {
  background(0,0,0);
  fill(255,255,255);
  textAlign(CENTER, CENTER);
  folder = cp5.get(DropdownList.class, "droplist").getValue();
  text(str(folder), width/2, 2 * height / 3);
}

However, this gives a NullPointerError.

I have seen a solution on the forum from several months ago, and tried implementing the following instead

void controlEvent(ControlEvent theEvent) {
  if (theEvent.isGroup()) {
    if (theEvent.group().name() == "droplist")
    folder = theEvent.group().value();
  } else if(theEvent.isController()) {
    //
  }
}

This causes an error since apparently the “name” and “value” functions do not exist. Changing these to “getName” and “getValue” also did not work.

I am fairly new to Processing, so I am sorry if what I have done is poorly written. Any help would be greatly appreciated.

Something like the following should work. DropdownList is deprecated according to the author and it is suggested that you use ScrollableList instead. There is an example in Files/Examples/ControlP5. I’ll let you add the folder list since that was unavailable in the code posted.

// DropdownList is DEPRECATED, 
// use ScrollableList instead, see example ControlP5scrollableList
  
import controlP5.*;
import java.util.*;

ControlP5 cp5;

String[] names = {"A", "B", "C", "D", "E"};

void setup() {
  size(400, 400);
  cp5 = new ControlP5(this);
  cp5.addScrollableList("dropdown")
    .setPosition(width/2 - 100, height/3 - 50)
    .setSize(200, 120)
    .setBarHeight(20)
    .setItemHeight(20)
    .setOpen(false)
    .addItems(names)
    ;
}

void draw() {
  background(0);
}

void dropdown(int n) {
  /* request the selected item based on index n */
  println(n, cp5.get(ScrollableList.class, "dropdown").getItem(n));
}

2 Likes

Thank you for this. After implementing your solution, I managed to get it to work. Thank you again.