java 内部类 修改局部变量,在内部类(java)中访问局部变量

I got two errors after I compiled my code.

The errors are:

1.

local variable input is accessed within inner class;

needs to be declared final

String name = input.getText();

2.

local variable c_age is accessed within inner class;

needs to be declared final

Object child_age = c_age.getSelectedItem();

This is my code:

import javax.swing.*;

import java.awt.event.*;

public class GUI

{

public static void main(String[] args)

{

JFrame frame = new JFrame("Try GUI");

JLabel l1 = new JLabel("Please Enter Your Child's Name");

JTextField input = new JTextField("",10);

JLabel l2 = new JLabel("Choose Your Child's Age");

String[] age = {"Age","1","2","3","4","5","6"};

JComboBox c_age = new JComboBox(age);

JButton button = new JButton("Search");

JTextArea result = new JTextArea();

JScrollPane extend_area = new JScrollPane(result);

button.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent ae)

{

String name = input.getText();

Object child_age = c_age.getSelectedItem();

}

});

JPanel panel = new JPanel();

panel.add(l1);

panel.add(input);

panel.add(l2);

panel.add(c_age);

panel.add(button);

panel.add(extend_area);

frame.add(panel);

frame.setSize(350,350);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

How can I solve this error?

解决方案

You need to declare

JTextField input = new JTextField("",10);

and

JComboBox c_age = new JComboBox(age);

like this:

final JTextField input = new JTextField("",10);

final JComboBox c_age = new JComboBox(age);

This means that input and c_age cannot change:

Any local variable, used but not

declared in an inner class must be

definitely assigned before the

body of the inner class.

Explanation taken from The Java Language Specification, Section - 8.1.3 Inner Classes and Enclosing Instances

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值