Dan
Dan

Reputation: 597

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?

Upvotes: 0

Views: 5962

Answers (2)

APerson
APerson

Reputation: 8422

Every time you add something new to the JFrame, it removes the thing that was previously in it.

You'll need to create a JPanel or some other container to hold the JCheckBoxes, and then put that inside the JFrame.

Also, you can keep track of the checkboxes in a List.

For instance:

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(BoxLayout.Y_AXIS, panel));
List<JCheckBox> checkboxes = new ArrayList<>();

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

frame.add(panel);

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347214

The main problem is, you're adding all the check boxes to the same location on the frame.

A JFrame uses a BorderLayout by default. A BorderLayout allows a single component to be managed in each of its five available slots. Basically a BorderLayout will ignore all but the last component added to any of the slots

Instead, try changing the LayoutManager to something more useful, like FlowLayout or GridBagLayout depending on your needs

Take a look at Laying Out Components Within a Container for more details.

Depending on your needs, I might be tempered to fill the ArrayList with the JCheckBoxes instead of String or even a Map of some kind, to make it easier to link the text with the JCheckBox

Upvotes: 1

Related Questions