无法在内部类中引用/修改非final变量

时间:2011-08-01 19:11:11

标签: java inner-classes

所以我得到的错误是:“不能参考以不同方法定义的内部空间内的非最终变量角色”。我希望能够将字符串roletype设置为该Dropdown中选择的任何get。如果不是我正在尝试下面的方式,我怎么能这样做,或者我只是在我正在尝试的代码中犯了一些愚蠢的错误?

谢谢, 猎食

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.*;
import javax.swing.event.*;

public class Funclass extends JFrame {

    FlowLayout layout = new FlowLayout();
    String[] skillz = {"Analytical", "Numerical", "Leadership",
        "Communication", "Organisation", "Interpersonal"};
    String[] rolez = {"Developer", "Sales", "Marketing"};
    String[] Industries = {"Consulting", "Tech"};
    String R1, R2, R3, R4, roletype;

    public Funclass() {
        super("Input Interface");
        setLayout(layout);
        JTextField Company = new JTextField("Company Name");
        JComboBox TYPE = new JComboBox(Industries);
        JList skills = new JList(skillz);
        JComboBox role = new JComboBox(rolez);
        skills.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(TYPE);
        add(skills);
        add(role);
        add(Company);

        ROLE.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    roletype = rolez[role.getSelectedIndex()];
                }
            }
        });
    }
}

3 个答案:

答案 0 :(得分:2)

您需要将role变量声明为final,以便内部类(ItemListener)可以访问它,如下所示:

final JComboBox role = new JComboBox(rolez); 

答案 1 :(得分:1)

import java.awt.event.*;
import javax.swing.*;

public class Funclass extends JFrame {

    private static final long serialVersionUID = 1L;
    private String[] rolez = {"Developer", "Sales", "Marketing"};
    private String roletype;
    private JComboBox role;

    public Funclass() {
        role = new JComboBox(rolez);
        role.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    roletype = role.getSelectedItem().toString();
                }
            }
        });
    }
}

答案 2 :(得分:0)

要从内部类访问外部类中的变量,必须将它们声明为final。因此,在这种情况下,role必须为final

编辑:roletype不需要声明final,即使它是在内部类中访问的,因为它是一个类变量,而不是方法变量。