I have a problem with ItemListeners. Basially, I want to query the database to get some data and put them into Objects following the DAO Pattern. The thing is, when I put an ArrayList
of CheakBoxes
, I can't figure out how to add Listeners to them.
I have tried to add ItemListener
before putting them in their container through loop. I have also tried to add ItemListeners after adding them to the container but also with no avail.
I have tested my script for 1 chekBox only, it works. When it comes to the ArrayList, i have this error Message: Cannot refer to the non-final local variable jCheckBox defined in an enclosing scope
The following code is another test, just to see if something was incorrect on my program, but it seems to give me same Issue when adding the listener to the ArrayList objects
package test;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private static ArrayList<JCheckBox> jCheckBoxs;
private static JFrame jFrame=new JFrame();
public static void main(String[] args) {
init();
}
private static void init() {
jFrame.setSize(new Dimension(400,400));
jFrame.setTitle("test");
JPanel jp=new JPanel();
jCheckBoxs=new ArrayList<JCheckBox>();
addArray("A");
addArray("B");
addArray("C");
jp.add(jCheckBoxs.get(0));
jp.add(jCheckBoxs.get(1));
jp.add(jCheckBoxs.get(2));
jFrame.getContentPane().add(jp);
jFrame.setVisible(true);
}
private static void addArray(String msg) {
JCheckBox jCheckBox=new JCheckBox();
jCheckBox.setText(msg);
jCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println(jCheckBox.getName());
}
});
}
}