从ActionListener内部更改变量 [英] Change Variable from the inside of a ActionListener

查看:123
本文介绍了从ActionListener内部更改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 ActionListener 内部更改变量?

Is it possible to change a variable from inside of a ActionListener?

我的意思是这样的:

    boolean test = false;

    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            test = true;
        }
    });

我想将 test 更改为true

I want to change test to true when someone presses the button.

推荐答案

我不确定这是否对您有帮助,但是如果您使用动作侦听器,猜测您正在使用Javaswing API。在那种情况下,您可能正在扩展类似 JFrame 之类的东西,或者类似的东西,因此您可以使用以下代码:

I'm not sure if this helps you but if you are using a action listener I'm guessing you are working with javas swing api. In that case you are maybe extending a class like JFrame or something like that so you could use this:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame {

    private boolean booleanToChange = false;

    private JButton exampleButton;

    public MyFrame() {
        exampleButton = new JButton();
        exampleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                //Access a member in anonymous class
                MyFrame.this.booleanToChange = true;
            }
        });
    }
}

此处解释为什么必须是最终的:)希望这会有所帮助

And here the explanation why it has to be final :) hope this helps a bit

这篇关于从ActionListener内部更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆