在封闭范围内定义的局部变量num必须是最终的或有效的最终

时间:2016-05-01 12:31:13

标签: java checkbox local final

点击删除button后,我希望它显示选中的checkbox。但是,它们是 num 下的红线,位于删除button代码中。

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

    }

错误

  

线程中的异常&#34; AWT-EventQueue-0&#34; java.lang.Error:未解决   编译问题:         在封闭范围内定义的局部变量num必须是最终的或有效的最终         在gui.deleteAdmin $ 1.actionPerformed(deleteAdmin.java:86)

我是否正确实施了它?

1 个答案:

答案 0 :(得分:0)

声明这个

int num;

作为类变量并在

中初始化它
public deleteAdmin()
    {
        num=0;