Your using a while
(while (e.next()) {
) to build portions of your program. Within it your a creating a new reference to lp
and JButton
, sabt
, on each iteration.
Your ActionListener
will only be able to reference the LAST instance of lp
created. This is most likely why you actionPerformed
is doing what you think it should be...
Think about it like this...if I do...
lp = new new LimitPanel(st, 6);
lp = new new LimitPanel(st, 6);
lp = new new LimitPanel(st, 6);
lp = new new LimitPanel(st, 6);
JCheckBox[] = lp.getChecks();
Which instance of lp
have I obtained the check boxes from??
Updated with more details
// Create a new instance of "LimitPanel"
lp = new LimitPanel(st, 6);
// You can check this by using the hashCode of the object...
System.out.println(lp.hashCode());
pn.add(lp);
JButton sabt = new JButton(" ثبت ");
sabt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
/*...*/
// Use what ever was last assigned to "lp"
jcb = lp.getChecks();
// You can check this by using the hashCode of the object...
System.out.println(lp.hashCode());
/*...*/
}
});
IF you really wanted to ensure that the ActionListener
was using a particular instance of LimitPanel
, you should pass that reference to a special instance of ActionListener
...
For example...
lp = new LimitPanel(st, 6);
// You can check this by using the hashCode of the object...
System.out.println(lp.hashCode());
pn.add(lp);
JButton sabt = new JButton(" ثبت ");
sabt.addActionListener(new LimitActionHandler(lp));
And the LimitActionHandler
...
public class LimitActionHandler implements ActionListener {
private LimitPanel limitPane;
public LimitActionHandler(LimitPanel limitPane) {
this.limitPane = limitPane;
}
@Override
public void actionPerformed(ActionEvent arg0) {
/*...*/
// Use what ever was last assigned to "lp"
jcb = limitPane.getChecks();
// You can check this by using the hashCode of the object...
System.out.println(limitPane.hashCode());
/*...*/
}
}
As I stated in my comments, I think it's a bad idea to expose the JCheckBox
es from the LimitPanel
, as it allows other parts of your application unrestricted access to those objects, which they don't need for there work...
JCheckBox[] jcb = limitPane.getChecks();
for (JCheckBox cb : jcb) {
cb.setSelected(false); //...
}
for (JCheckBox cb : jcb) {
cb.getParent().remove(cb); //...
}
This is very dangerous. You can argue that your application won't do these things, but you can't stop it from happening...