Cannot refer/modify non-final variable in an innerclass

喜夏-厌秋 提交于 2019-12-12 10:47:31

问题


So I'm getting the error: "CANNOT REFER TO A NON-FINAL VARIABLE ROLE INSIDE AN INNERCLASS DEFINED IN A DIFFERENT METHOD". I want to be able to set the string roletype to whatever get's selected in that Dropdown. How can I do this if not in the way I'm trying below, or am I simply making some stupid error in the code I'm trying?

Thanks, Ravin

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

回答1:


You need to declare the role variable as final so that the inner class (ItemListener) can have access to it, like so:

final JComboBox role = new JComboBox(rolez); 



回答2:


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



回答3:


To access variables in the outer class from an inner class, they must be declared final. So in this case, role must be final.

EDIT: roletype does not need to be declared final even though it's accessed in the innerclass because it is a class variable, not a method variable.



来源:https://stackoverflow.com/questions/6903145/cannot-refer-modify-non-final-variable-in-an-innerclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!