1

我有以下代码,在第 19 行出现错误“无法为最终变量计数分配值”,但我必须将此变量分配为最终变量才能在“监听器”中使用它。错误在哪里?

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

3 回答 3

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);
    }
}
于 2013-02-11T15:11:13.620 回答
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");
        }
    }
于 2013-02-11T15:10:42.963 回答
1

在 ClickListener 中移动变量,这才是你真正想要的。如果您将变量移到类之外,它必须是最终的,因为它将被视为常量。

于 2013-02-11T15:10:56.243 回答