用于检测变量更改的 Java 事件侦听器

2022-09-03 05:51:24

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

请问我似乎在任何地方都找不到解决这个问题的方法,我发现这个网站解释了如何创建自定义事件


答案 1

就像您需要创建事件侦听器一样,您还需要创建事件触发器 - 因为没有自动操作可以为您执行此操作。我提供了示例代码,向您展示了如何实现这样的 firer。

此测试实现并不完美。它仅包括一种添加侦听器的方法。您可能希望包含一种方法来删除不再对接收事件感兴趣的侦听器。另请注意,此类不是线程安全的。

import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue; 

/**
 * This class uses the EventQueue to process its events, but you should only 
 * really do this if the changes you make have an impact on part of a GUI 
 * eg. adding a button to a JFrame.
 *
 * Otherwise, you should create your own event dispatch thread that can handle
 * change events
 */
public class BooleanChangeTest implements BooleanChangeDispatcher {

    public static void main(String[] args) {

        BooleanChangeListener listener = new BooleanChangeListener() {
            @Override
            public void stateChanged(BooleanChangeEvent event) {
                System.out.println("Detected change to: "
                    + event.getDispatcher().getFlag()
                    + " -- event: " + event);
            }
        };

        BooleanChangeTest test = new BooleanChangeTest(false);
        test.addBooleanChangeListener(listener);

        test.setFlag(false); // no change, no event dispatch
        test.setFlag(true); // changed to true -- event dispatched

    }

    private boolean flag;
    private List<BooleanChangeListener> listeners;

    public BooleanChangeTest(boolean initialFlagState) {
        flag = initialFlagState;
        listeners = new ArrayList<BooleanChangeListener>();
    }

    @Override   
    public void addBooleanChangeListener(BooleanChangeListener listener) {
        listeners.add(listener);
    }

    @Override
    public void setFlag(boolean flag) {
        if (this.flag != flag) {
            this.flag = flag;
            dispatchEvent();
        }
    }

    @Override
    public boolean getFlag() {
        return flag;
    }

    private void dispatchEvent() {
        final BooleanChangeEvent event = new BooleanChangeEvent(this);
        for (BooleanChangeListener l : listeners) {
            dispatchRunnableOnEventQueue(l, event);
        }
    }

    private void dispatchRunnableOnEventQueue(
                final BooleanChangeListener listener, 
                final BooleanChangeEvent event) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                listener.stateChanged(event);
            }
        });
    }

}

interface BooleanChangeDispatcher {

    public void addBooleanChangeListener(BooleanChangeListener listener);
    public boolean getFlag();
    public void setFlag(boolean flag);

}

/**
 * Listener interface for classes interested in knowing about a boolean
 * flag change.
 */
interface BooleanChangeListener extends EventListener {

    public void stateChanged(BooleanChangeEvent event);

}

/** 
 * This class lets the listener know when the change occured and what 
 * object was changed.
 */
class BooleanChangeEvent extends EventObject {

    private final BooleanChangeDispatcher dispatcher;

    public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
        super(dispatcher);
        this.dispatcher = dispatcher;
    }

    // type safe way to get source (as opposed to getSource of EventObject
    public BooleanChangeDispatcher getDispatcher() {
        return dispatcher;
    }
}

答案 2

使用属性更改支持。您不必实现那么多,而且它是线程安全的。

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...");
    }
}