dimanche 1 mai 2016

Local variable num defined in an enclosing scope must be final or effectively final

When delete button is clicked, I want it to display which checkbox is checked. However, they are a red line under num which is in delete button code.

for(int i=0;i<num;i++)

deleteAdmin.java

public deleteAdmin()
    {
        int num=0;

        JButton back= new JButton("Back");
        JButton delete= new JButton("Delete");

       JPanel topPanel = new JPanel(new GridLayout(1, 0, 3, 3));
        topPanel.add(back);
        topPanel.add(delete);


        adminAPI admin = new adminAPI();
        List<String>allName = null;

        try {
            allName= admin.displayName(); // retrieve all names from MySQL and store to list
            num= admin.displayCheckBoxAndLabel(); // get total row numbers
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Object [] o1=allName.toArray(); // convert arrayList to array
        JCheckBox[] checkBoxList = new JCheckBox[num];

        JPanel checkBoxPanel= new JPanel(new GridLayout(0,5,5,5));
        for(int i = 0; i < num; i++) {  
            checkBoxList[i]= new JCheckBox(""+o1[i]); // replace each checkbox with name
            checkBoxPanel.add(checkBoxList[i]);

        }

          delete.addActionListener(new ActionListener(){ // if delete button clicked
                public void actionPerformed(ActionEvent e)
                {
                    for(int i=0;i<num;i++)
                    {
                        if(checkBoxList[i].isSelected())
                            System.out.println(i);
                    }
                }


            });

         setLayout(new BorderLayout(5, 5));
          add(topPanel, BorderLayout.PAGE_START);
           add(checkBoxPanel, BorderLayout.CENTER);
           setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    }

Error

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: Local variable num defined in an enclosing scope must be final or effectively final at gui.deleteAdmin$1.actionPerformed(deleteAdmin.java:86)

Am I implementing it correctly ?




Aucun commentaire:

Enregistrer un commentaire