Search code examples
javaarraysswingjcheckbox

Variable content (String) to access JCheckBox's methods


I have this array:

String extras[] = new String[6];

extras[0] = "bacon";
extras[1] = "potato";
extras[2] = "chicken";
extras[3] = "cheese";
extras[4] = "olive";
extras[5] = "tomato";

and this arrayList:

ArrayList selectedExtra = new ArrayList();

I am trying to get only the selected itens, so I have this for loop:

for (int i=0; i<extras.length ; i++){

       String aditional = extras[i]; //get each extra name

       if(aditional.isSelected()){  // thats my problem
       selectedExtra.add(adicional); // add the selected extras 

        }
     }

I am trying to attribute each String, lets say "Bacon", and use it to check whether or not the JCheckBox with that name is selected, and if it is, attribute that to my arrayList.

Yes, the array items' names are exactly identical to the JCheckBox's names.

How can I get it done?? Thanks!


Solution

  • It seems over complicated to put the String representation into an Array and then try to get the Object. Why not just store the actual JCheckBox's in the Array:

    JCheckBox[] extras = new JCheckBox[6];
    //add items
    
    //Don't use raw types! 
    ArrayList<JCheckBox> selectedExtra = new ArrayList<>();
    
    for (int i=0; i<extras.length ; i++){
        if(extras[i].isSelected()){  
           selectedExtra.add(extras[i]); // add the selected extras 
        }
     }