无法从actionlistener内部增加变量

yuvru6vn  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(358)

我是java新手,刚刚开始学习我想通过点击按钮来增加一个变量,但是我得到了以下错误

local variables referenced from an inner class must be final or effectively final

The assigned value is never used

添加final并不能解决问题,我有点纠结为什么这不起作用?你能帮忙吗?

public class JavaApplication2 {
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton button = new JButton("Click");

        panel.setLayout(new FlowLayout());

        frame.add(panel);
        panel.add(button);

        int x;
        x = 0;

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("You CLicked the Button " + x + " times");  
                x = x + 1; // *getting error*
            }
        });

        frame.setVisible(true);
        frame.setSize(500,500);
        frame.setLocation(50,50);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
5anewei6

5anewei61#

你的变量 X 必须是全局静态变量,因为您永远不知道 ActionListener 将被触发。 X 不在该范围内,此时可能已删除。

biswetbf

biswetbf2#

我强烈建议使用如下的方法。
对于这样的问题,不应该使用全局静态变量。

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JavaApplication2 {
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton button = new JButton("Click");

        panel.setLayout(new FlowLayout());

        frame.add(panel);
        panel.add(button);

        Counter c = new Counter();

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("You CLicked the Button " + c.getValue() + " times");
                c.increment();
            }
        });

        frame.setVisible(true);
        frame.setSize(500, 500);
        frame.setLocation(50, 50);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

class Counter {
    private int value = 0;

    void increment() {
        value++;
    }

    void reset() {
        value = 0;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

}

相关问题