简体   繁体   中英

Cannot refer/modify non-final variable in an innerclass

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

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

final JComboBox role = new JComboBox(rolez); 
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();
                }
            }
        });
    }
}

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.

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