简体   繁体   中英

Trying to add item listener to a JCheckBox object

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]);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM