Java事件侦听器以检测变量更改 [英] Java Event Listener to detect a variable change

查看:52
本文介绍了Java事件侦听器以检测变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在我的问题的任何地方找到答案.是否有任何事件侦听器可以检测布尔值或其他变量的变化,然后对其进行操作.还是可以创建一个自定义事件侦听器来检测到这一点?

I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it possible to create a custom event listener to detect this?

请我似乎在任何地方都找不到解决方案,我发现此网站解释了如何创建自定义事件

Please I cannot seem to find a solution to this anywhere and I found this website explaining how to create custom events

推荐答案

使用PropertyChangeSupport .您无需执行太多操作,而且它是线程安全的.

Use PropertyChangeSupport. You wont have to implement as much and it is thread safe.

public class MyClassWithText {
    protected PropertyChangeSupport propertyChangeSupport;
    private String text;

    public MyClassWithText () {
        propertyChangeSupport = new PropertyChangeSupport(this);
    }

    public void setText(String text) {
        String oldText = this.text;
        this.text = text;
        propertyChangeSupport.firePropertyChange("MyTextProperty",oldText, text);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }
}

public class MyTextListener implements PropertyChangeListener {
    @Override
    public void propertyChange(PropertyChangeEvent event) {
        if (event.getPropertyName().equals("MyTextProperty")) {
            System.out.println(event.getNewValue().toString());
        }
    }
}

public class MyTextTest {
    public static void main(String[] args) {
        MyClassWithText interestingText = new MyClassWithText();
        MyTextListener listener = new MyTextListener();
        interestingText.addPropertyChangeListener(listener);
        interestingText.setText("FRIST!");
        interestingText.setText("it's more like when you take a car, and you...");
    }
}

这篇关于Java事件侦听器以检测变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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