0

I am trying add an item listener to a checkbox to see if its been checked, and if it is, to be added to a list of SQL table names to be selected. Inversely, if it is not selected then remove it from the list. I cannot add a listener though to any checkbox because "they are not effitively final". What can I do/is there a better way to attack it?

My method:

public JPanel drawChecks(){

 ArrayList<String> list = MainFrame.grabSQLTableNames();   
 int index = list.size();
 int rows = 1;
 while(index > 1){
 rows++;
 index = index - 3;   
 }

GridLayout c = new GridLayout(rows, 3);
JPanel panel = new JPanel(c);
JCheckBox check[] = new JCheckBox[list.size()];

for(int x = 0; x < list.size(); x++){

 check[x] = new JCheckBox(list.get(x));
 check[x].setVisible(true);
 check[x].addItemListener(new ItemListener() {
  public void itemStateChanged(ItemEvent e) {
    if (check[x].getState == true){

        //do something

       }
     }
    });
 panel.add(check[x]);
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
JJ Jansen
  • 1
  • 3

1 Answers1

1

Get the source of the event using the getSource method of the ItemEvent

public void itemStateChanged(ItemEvent e) {
    JCheckBox checkBox = (JCheckBox)e.getSource();
    if ( checkBox.isSelected() ){
        //do something
    }
}

For future reference, please read the following for tips on posting code examples for asking questions on stack overflow: https://stackoverflow.com/help/mcve

Community
  • 1
  • 1
copeg
  • 8,290
  • 19
  • 28