Cannot reference / modify non-final variable in inner class

So, I get the error message: "THE UNFINISHED VARIABLE ROLE IN THE INERCLEAS DETERMINED BY DIFFERENT METHOD" CAN NOT MEET. I want to set the role type of the string to everything that is selected in this folder. How can I do this if not the way I'm trying to do below, or am I just making some kind of stupid mistake in the code I'm trying to do?

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()]; } } }); } } 
+6
source share
3 answers

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

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

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

EDIT: roletype does not need to be declared final , although it is available in the inner class because it is a class variable, not a method variable.

0
source

Source: https://habr.com/ru/post/894052/


All Articles