Java Event Listener to detect a variable change

前端 未结 7 1714
逝去的感伤
逝去的感伤 2021-02-05 14:38

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 p

相关标签:
7条回答
  • 2021-02-05 15:30

    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...");
        }
    }
    
    0 讨论(0)
提交回复
热议问题