Reputation: 101
I'm writing a swing application in java and I have 10 jPanel with 10 jCheckBox in each one. The names of the jPanels are jPanel1, jPanel2, etc; and the names of the jCheckBox in jPanel1 are jCheckBox1_1, jCheckBox1_2, jCheckBox1_3, etc, and similar for the others jPanels. In a moment I need to know which of those jcheckboxes have been checked by the user so I do this
boolean[] selected=new boolean[100];
for(int i=0; i<selected.length; i++)
selected[i]=false;
if(jPanel1.jCheckBox1_1.isSelected())
selected[0]=true;
if(jPanel1.jCheckBox1_2.isSelected())
selected[1]=true;
if(jPanel1.jCheckBox1_3.isSelected())
selected[2]=true;
and continue with the rest
I should do this way because I use the jCheckBoxes (for seeing if they are checked) in a jFrame, not in their jPanels. The problem is that I have to write a lot of repetitive code, and I think that is not intelligent. So I wonder if I can "recover" those objects and use them by their String names. For example:
String[] name=new String[100];
JCheckBox[] checkbox=new JCheckBox[name.length];
for(int i=0; i<100; i++){
int num_panel=i/10+1;
name[i]="jPanel"+num_panel+".jCheckBox"+num_panel+"_"+(i%10+1);
}
//and now use those names to ask if those jcheckBoxes are checked
boolean[] selected=new boolean[100];
for(int i=0; i<100; i++){
if(name[i].isSelected()) //but this isn't right because its a String, not a jCheckBox
selected[i]=true;
else
selected[i]=false;
}
So I would like to know if you know any way how I can use those jCheckBoxes by their string name. I know that I could have created them programatically as an array and everything would be easier, but other problem is that because its a swing gui, it's so hard to design them programatically. Thanks in advance.
Upvotes: 0
Views: 239
Reputation: 23629
Two solutions:
Upvotes: 2