I want a selected ListBox item appear in red and stay that way until I make another selection. How can I do this? At the moment it stays red as I click and hold down the mouse key then reverts to the original background color after I have let go. Is this the function of the method .setColorActive()?, or should it permanently change to the color I specified after it has been clicked? My code is below. Thanks.
list = controlp5.addListBox("LIST")
.setPosition(130, 40)
.setSize(100, 150)
.setItemHeight(20)
.setBarHeight(20)
.setColorBackground(color(40, 128))
.setColorActive(color(255, 0, 0))
As far as I could tell from the source code, there is no value to keep track wether a controller is selected or not. However, you can manually keep track using the controlEvent listener and manually change the background colour as a quick and hacky workaround:
import controlP5.*;
ControlP5 controlp5;
ListBox list;
int selectedIndex = -1;//no selection initially
int colourBG = 0xffff0000;
int colourSelected = 0xffff9900;
void setup(){
size(400,400);
controlp5 = new ControlP5(this);
list = controlp5.addListBox("LIST")
.setPosition(130, 40)
.setSize(100, 150)
.setItemHeight(20)
.setBarHeight(20)
.setColorBackground(colourBG)
.setColorActive(colourSelected);
for (int i=0;i<80;i++) {
ListBoxItem lbi = list.addItem("item "+i, i);
lbi.setColorBackground(colourBG);
}
}
void draw(){
background(255);
}
void controlEvent(ControlEvent e) {
if(e.name().equals("LIST")){
int currentIndex = (int)e.group().value();
println("currentIndex: "+currentIndex);
if(selectedIndex >= 0){//if something was previously selected
ListBoxItem previousItem = list.getItem(selectedIndex);//get the item
previousItem.setColorBackground(colourBG);//and restore the original bg colours
}
selectedIndex = currentIndex;//update the selected index
list.getItem(selectedIndex).setColorBackground(colourSelected);//and set the bg colour to be the active/'selected one'...until a new selection is made and resets this, like above
}
}
So in the example above, selectedIndex stores the previous/most recent selection as a list index. This is then used in the controlEvent handler. If there was a selection previously made, restore the normal background colour. Then carry on setting the selected index to the most recently selecting and setting the background colour as the active one, so visually it looks selected.
This is a manual/hacky approach. A longer version would involve either extending the ListBox java class and adding this functionality in, or editing the controlP5 source code, recompiling the library and using the custom version.