user1300459
user1300459

Reputation: 23

How to access dynamically created element (JAVA)?

I have dynamically created several jCheckBox elements:

for (j=0;j<j1;j++){
   final JCheckBox cb = new JCheckBox("");
   cb.setText(col_name);
   mainPanel12.add(cb,BorderLayout.NORTH);
   mainPanel12.repaint();
...
}

How can i access some particular checkboxes outside the loop as they all have the same name cb?

Upvotes: 2

Views: 563

Answers (4)

Omaha
Omaha

Reputation: 2292

You could create a data structure outside the loop in order to record each value of cb as you create new objects. The easiest way would be to have a container of some sort (perhaps an array or java.util.List) that will contain all of the checkboxes:

JCheckBox[] cbs=new JCheckBox[j1];

for (j=0;j<j1;j++)   {
    final JCheckBox cb = new JCheckBox("");
    cb.setText(col_name);
    mainPanel12.add(cb,BorderLayout.NORTH);
    mainPanel12.repaint();

    ...

    cbs[j]=cb;
}

Now you can refer to checkboxes by indexing elements of the array outside the loop.

Upvotes: 0

Android Killer
Android Killer

Reputation: 18489

Take one HashMap of Integer and jCheckBox like this outside for loop as intance variable:

Map<Integer,JCheckBox> map = new HashMap<Integer,JCheckBox>();
for (j=0;j<j1;j++){
   final JCheckBox cb = new JCheckBox("");
   cb.setText(col_name);
   mainPanel12.add(cb,BorderLayout.NORTH);
   mainPanel12.repaint();
   map.put(j,cb);
...
}

outside loop you can use like this;

JCheckBox = map.get(index_value_of_checkbox);

or

for(int i = 0; i<map.size(); ++i)
JCheckBox cb = map.get(i);

Upvotes: 2

Ondrej Kvasnovsky
Ondrej Kvasnovsky

Reputation: 4643

You have to get the components from the panel mainPanel12 and iterate over the collection. You can set a name to your component and then try to search for a component with that name.

for (j=0;j<j1;j++){
   final JCheckBox cb = new JCheckBox("");
   cb.setText(col_name);
   cb.setName(String.toString(j);
   mainPanel12.add(cb,BorderLayout.NORTH);
   mainPanel12.repaint();
...
}

Component[] comps = mainPanel12.getComponents();
for (j=0;j<mainPanel12.size();j++){
   Component c = comps[i];
   if("1".equals(c.getName())) {
       // and here is your component :-)
   }
}

Upvotes: 1

JTeagle
JTeagle

Reputation: 2196

That variable name is only accessible within the loop, so it would be of no use anyway. Have you considered member variables in the class in which you call this piece of code? An array of JCheckBoxes, if necessary.

Upvotes: 1

Related Questions