不能引用非最终变量
我正在尝试用 Java 创建简单的 GUI 程序,但找不到正确的解决方案来解决错误无法引用在不同方法中定义的内部类中的非最终变量。
这是到目前为止我的小代码;
myPanel = new JPanel();
JButton myButton = new JButton("create buttons");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int val = Integer.parseInt(textfield.getText());
for(int i = 0; i < val; i++) {
JButton button = new JButton("");
button.setText(String.valueOf(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickButton(i);
}
});
myPanel.add(button);
myPanel.revalidate();
}
}
});
也许我的做法是完全错误的。我想做的是;我想创建一组按钮,并说当用户按下按钮时我想显示一条消息,例如“您按下了按钮 4”或“您按下了按钮 10”。
I'm trying to create simple GUI program in Java and I couldn't find a proper solution to error cannot refer to a non-final variable inside an inner class defined in a different method.
Here's my small code so far;
myPanel = new JPanel();
JButton myButton = new JButton("create buttons");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int val = Integer.parseInt(textfield.getText());
for(int i = 0; i < val; i++) {
JButton button = new JButton("");
button.setText(String.valueOf(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickButton(i);
}
});
myPanel.add(button);
myPanel.revalidate();
}
}
});
Maybe my approach is completely wrong. What I'm trying to do is; I want to create a set of buttons and say when the user presses a button I want to display a message like "you pressed the button 4", or "you pressed the button 10".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
i
必须是最终的,内部类才能访问它。您可以通过将其复制到最终变量来解决此问题。但我建议将
for
循环的内容重构为一个单独的方法,如下所示:i
has to be final in order for the inner class to access it. You can work around this by copying it to a final variable.But I'd recommend refactoring the contents of the
for
loop into a separate method like this:为了避免这个问题,您必须将 myPanel 声明为类的成员变量,或者使用其他引用类成员的变量。
To avoid this problem, you have to either declare the myPanel as a member variable of the class or use something else that refers to the member of the class.
匿名类只能使用声明为final的局部变量,以保证它们不会改变。
Anonymous class can only use local variables declared as final so that they are guaranteed not to change.