Search code examples
javastringtogglebutton

Java - selecting a togglebutton from a String


Let's say i have many toggle buttons and i would like to change their state based on a condition, like this: if(something){buttonone.setSelected(true);}

The problem is, i have more than a 100 buttons and it would be a lot of time to write the conditions one by one.

Is it possible to get the buttons from a string and toggle the desired ones?

String buttontext="buttonone, buttontwo, buttonthree";

(button from the string).setSelected(true);

I'm new to Java, and i can't find an aswer to this. Thanks!


Solution

  • Place the buttons into an ArrayList or other collection and use a for loop through them, setting them selected if they match criteria. Also as noted in comments, if you use a HashMap<String, JToggleButton>, you can easily obtain a reference to the button of interest by its String "key", and then do what you wish with it.