Jhonatan Cruz
Jhonatan Cruz

Reputation: 75

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!

Upvotes: 1

Views: 50

Answers (3)

Jhonatan Cruz
Jhonatan Cruz

Reputation: 75

I got around it with a much dirtier solution. I test if each selectedExtra is selected, and if so, I check if the array already contains the word I am looking for in it; if not, I add the word to it.

 if (!selectedExtra.contains("Bacon") && bacon.isSelected()) {
            selectedExtra.add("Bacon");
    }   

Do that to each item.

ps: gonna leave it open a bit longer in case anyone come to a better solution to maybe help others!

Upvotes: 0

GBlodgett
GBlodgett

Reputation: 12819

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 
    }
 }

Upvotes: 3

DudeDoesThings
DudeDoesThings

Reputation: 729

You could have a HashMap which maps Strings (the names of your extras) to JCheckBox instances. Then you can do a lookup in that hashmap with the String to get the apropriate checkbox to check if it is selected.

Something like this: (of course this is heavily simplified)

private final Map<String, JCheckBox> boxes = new HashMap<>();

{
    String[] extras = {"Bacon"};

    boxes.put("bacon", new JCheckBox("Bacon"));

    for (String extra : extras) {
        if (boxes.get(extra).isSelected()) {
            // do stuff
        }
    }
}

Of course a much cleaner option would be to use an Enum for the extras. Then you could use an EnumMap for the JCheckBox instances.

Upvotes: 3

Related Questions