无法引用/修改内部类中的非最终变量 [英] Cannot refer/modify non-final variable in an innerclass

查看:57
本文介绍了无法引用/修改内部类中的非最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我收到错误消息:无法引用用不同方法定义的内部类中的非最终变量角色".我希望能够将字符串角色类型设置为在该下拉列表中选择的任何内容.如果不按照下面的方式进行操作,该怎么办?或者我只是在尝试的代码中犯了一些愚蠢的错误?

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?

谢谢, 拉文

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)可以访问它,如下所示:

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

这篇关于无法引用/修改内部类中的非最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆