gpt4 book ai didi

java - 在内部类中访问局部变量(java)

转载 作者:太空狗 更新时间:2023-10-29 22:33:50 25 4
gpt4 key购买 nike

编译代码后出现两个错误。

错误是:

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

这是我的代码:

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

}

我该如何解决这个错误?

最佳答案

你需要声明

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

JComboBox c_age = new JComboBox(age);

像这样:

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

final JComboBox c_age = new JComboBox(age);

这意味着inputc_age 不能改变:

Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.

解释取自 The Java Language Specification,Section - 8.1.3 Inner Classes and Enclosing Instances

关于java - 在内部类中访问局部变量(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5644334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com