我有下面的代码,我在第19行得到一个错误“无法为最终变量计数赋值”,但我必须将该变量指定为final以便在“LISTENER”中使用它。错误在哪里?Actionevent最终变量?
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);
}
}
Thx perfect!它的工作原理,但我不能声明类静态 – Alpan67 2013-02-11 15:16:21
你将不得不把它从主要的方法,并在'ButtonTester'类中声明它。或者,如果您有其他代码未显示,则可能无法将其设置为静态。尽可能使嵌套类静态是一个好习惯。如果你不能那么好。 – wolfcastle 2013-02-11 15:52:08