I have a basic understanding of how to create A(1) check box, and repeating that method over and over again to create more. However, this makes for messy as shit code, plus I don't feel like doing this method 30 times to create the needed 30 check boxes. So I figured a loop is my best bet and came up with:

JCheckBox ChckBxNme;

String[] anArray = { “one”,”two”,”three”}
for(int x = 0; x < anArray.length; x++){

ChckBxNme = new JCheckBox(anArray[x] );


Code works, but what I would expect is 3 use-able check boxes, but that isn't the case. I get one check box with labeling of what ever string value is in the last element of the array.

I narrowed the problem down to the reference: JCheckBox ChckBxNme; which is out side of the loop. Since there is only one JCheckBox being referenced, the loop just updates said singular reference.

So the question is, how do I make the reference... dynamic so that instead of 1 check box I get multiple, also that whole ChckBxNme is annoying and I would love to use the names in the array as the ChckBxNme, so the reference would be something like JCheckBox anArray[x]. However I know this doesn't work, I get the error that an "object" was expected and not a string.

Also, for right now I'm not worried about "using" the checkboxes for now.

for(String name : chkNms) {

	    JCheckBox checkBox = new JCheckBox(name);


Solved using the above code provided by a buddy.

Member Avatar


Or, you could use...

String anArray[] = { “one”,”two”,”three”}
JCheckBox ChckBxNme[] = new JCheckBox [anArray.length];  // This creates the required number of JCheckBoxes based on the number of item in your String array

for(int x = 0; x < anArray.length; x++){

ChckBxNme[x] = new JCheckBox(anArray[x] );