我有以下代码,我在第19行得到错误“无法为最终变量计数赋值”,但我必须将此变量指定为final才能在“LISTENER”中使用它。错误在哪里?
import java.awt.event.*;
import javax.swing.*;
public class ButtonTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JButton button = new JButton();
frame.add(button);
final int count = 0;
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
count++;
System.out.println("I was clicked " + count + " times");
}
}
ActionListener listener = new ClickListener();
button.addActionListener(listener);
frame.setSize(100,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 0 :(得分:4)
分配后,final
变量无法修改。解决方案是使变量成为ClickListener类的成员:
import java.awt.event.*;
import javax.swing.*;
public class ButtonTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JButton button = new JButton();
frame.add(button);
class ClickListener implements ActionListener
{
int count = 0;
public void actionPerformed(ActionEvent event)
{
count++;
System.out.println("I was clicked " + count + " times");
}
}
ActionListener listener = new ClickListener();
button.addActionListener(listener);
frame.setSize(100,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 1 :(得分:2)
您在ClickListener
类中使用count,但它在类之外声明。您只在ClickListener
内使用它,因此请在那里移动声明。也可以使类静态:
static class ClickListener implements ActionListener
{
private int count = 0;
public void actionPerformed(ActionEvent event)
{
count++;
System.out.println("I was clicked " + count + " times");
}
}
答案 2 :(得分:1)
在ClickListener中移动变量,这就是你真正想要的。 如果将变量移到类之外,它必须是最终的,因为它将被视为常量。