Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()];
                }
            }
        });
    }
}
like image 399
Ravin Avatar asked Aug 01 '11 19:08

Ravin


1 Answers

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); 
like image 91
João Silva Avatar answered Nov 15 '22 00:11

João Silva