heyitsmyusername heyitsmyusername - 5 months ago 17
Java Question

Java: Array list of objects & getting values/properties of automatically created checkboxes

I have a

ArrayList
of Strings that automatically generates a list of check-boxes (of varying count) in a popup window. I currently have two problems with the below code:


  • Object[] params
    doesn't work because it requires me to know the size of the ArrayList
    ar
    in advance, and I havent figured out to get an arraylist of objects to work with my code. How can I fix this? I tried creating an arraylist of objects, but I could only get it to display nonsensical text.

  • How can I get the values/text of each checkbox and it's respective isSelected() state?



Below is my code:

String message = "The selected servers will be shutdown.";
Object[] params = {message, null, null, null, null, null};

ArrayList<String> ar = GetSet.getStopCommand(); // Example array: ./Stopplm11.sh|./Stopplm12.sh|./Stopplm14.sh|./Stopplm15.sh

for(int i=0; i< ar.size(); i++){
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
params[i+1]= checkbox;
}

int n = JOptionPane.showConfirmDialog(btnShutdownServer, params, "Shutdown Servers", JOptionPane.OK_CANCEL_OPTION);

if (n == JOptionPane.OK_OPTION){
// DO STUFF
//boolean buttonIsSelected= checkbox.isSelected();
}else{
// user cancelled
}


An image, for those who like images:

Image for those who like images

Answer

You can make it an ArrayList of JCheckBox:

ArrayList<JCheckBox> checkboxes = new ArrayList<JCheckBox>();

Then you can do:

for(int i = 0; i < ar.size(); i++)
{
    JCheckBox checkbox = new JCheckBox();
    checkbox.setText(ar.get(i).toString());
    checkbox.setSelected(true);

    // add the checkbox to the ArrayList
    checkboxes.add(checkbox);
}

Finally, to check the state of all checkboxes in your if condition, you can simply do:

if (n == JOptionPane.OK_OPTION){
    // DO STUFF
    //boolean buttonIsSelected= checkbox.isSelected();

    // loop through all checkboxes in the ArrayList
    for (JCheckBox checkbox : checkboxes)
    {
        // current one is selected
        boolean buttonIsSelected = checkbox.isSelected();
    }

    // rest of code in if condition
}
Comments