有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法引用/修改innerclass中的非最终变量

所以我得到了一个错误:“不能引用在另一个方法中定义的内部类中的非最终变量角色”。我希望能够将字符串roletype设置为下拉列表中选择的任何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) 个答案

  1. # 1 楼答案

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

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

  2. # 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. # 3 楼答案

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

    final JComboBox role = new JComboBox(rolez);