Search code examples
javaarraysswingjcheckbox

Can you create on the fly references to JCheckBox objects?


I am not sure how to ask this. The program I am working on is done, but it seems like it has excessive code. Here is part of the code:

chkDef1 = new JCheckBox

if (chkDef1.isSelected()) {
            actual = chkDef1.getText();
        } 
else if (chkDef2.isSelected()) {
            actual = chkDef2.getText();
        } 
else if (chkDef3.isSelected()) {
            actual = chkDef3.getText();
        } 
else {
            actual = chkDef4.getText();
        }

There are other areas where there is a lot of duplicate code with the chkDef1 - 4 checkboxes. What I would like to do is use a loop in the areas where the code is duplicated and then just use 1 assignment statement.

I've tried : if(('chkDef' + counter).isSelected())

I've also tried assigning "'chkDef' + counter" to a String variable and then adding isSelected. Unfortunately I keep getting error messages.

I am a novice programmer so I do not know if what I want to do is possible or what it is called. If it is possible an explanation of how would be appreciated.


Solution

  • Simply create a list of checkboxes and iterate through it.

    ArrayList<JCheckBox> checkboxes  = new ArrayList<JCheckBox>();
    //Init your checkboxes array. 
    
    for(JCheckbox chkbox :checkboxes)
    {
      if(chkbox.isSelected())
       {
        actual = chkbox.getText() ; break;
      }
    }
    

    Although, there could be a JCheckbox group that does what you want.

    Looks like you can use ButtonGroup and get the elements to iterate through it.