samedi 7 février 2015

How to create JCheckBox for elements of an ArrayList

I have an array that fills in by the user. Then each element of this array will be a CheckBox. For example if the array has 6 elements, it must create 6 checkboxes.


This is how I tried to loop through the array and create the checkbox, but it only overwrite on one checkbox.



public static void main(String[] args) {
JFrame frame = new JFrame("Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);

ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("checkbox 1");
myArrayList.add("checkbox 2");
myArrayList.add("checkbox 3");
myArrayList.add("checkbox 4");
myArrayList.add("checkbox 5");

for(String element : myArrayList){
JCheckBox box = new JCheckBox(element);
frame.add(box);
}

frame.setVisible(true);
}


It is important that I have the access to each single checkbox later, so I can specify for example if checkbox2 is selected, do this.


So is there any way to make these checkboxes dynamically according to the ArrayList's size?





Aucun commentaire:

Enregistrer un commentaire