Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java PropertyChangeListener

Tags:

java

I'm trying to figure out how to listen to a property change in another class. Below is my code:

ClassWithProperty has the property I want to listen to:

public class ClassWithProperty {
    private PropertyChangeSupport changes = new PropertyChangeSupport(this); 
    private int usersOnline;

    public int getUsersOnline() {
        return usersOnline;
    }

    public ClassWithProperty() {
        usersOnline = 0;
        while (usersOnline<10) {
            changes.firePropertyChange("usersOnline", usersOnline, usersOnline++);
        }
    }

    public void addPropertyChangeListener(
        PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }
    public void removePropertyChangeListener(
        PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }
}

Main is where i need to know about the property change:

public class Main {

    private static ClassWithProperty test;

    public static void main(String[] args) {
        test = new ClassWithProperty();
        test.addPropertyChangeListener(listen());

    }

    private static PropertyChangeListener listen() {
        System.out.println(test.getUsersOnline());
        return null;
    }

}

I have the event fired only the last time (usersOnline=10). I'm new to Java and tried to find a solution, but to no avail.

like image 290
Laphroaig Avatar asked Feb 13 '11 22:02

Laphroaig


1 Answers

What I do is put a method in the ClassWithProperty class:

public PropertyChangeSupport getPropertyChangeSupport() {
    return changes;
}

Then, register for property change events in the constructor of your Main() class:

private void initializeListeners() {
    test.getPropertyChangeSupport().addPropertyChangeListener((PropertyChangeEvent event) -> {
        if (event.getPropertyName().equals("usersOnline"))   {
            String passedEventData = (String) event.getNewData(); 
        }
    });
}

This make it so you are not repeating the code in your ClassWithProperty with methods that are already in the PropertyChangeSupport class.

when you need to fire an event in your ClassWithProperty class, do:

changes.firePropertyChange("usersOnline", oldValue, newValue);

One notable feature of this method is that, if the
event.getOldValue() and the event.getNewValue() are equal, the event will not fire. If you want to fire repeated events with the same information, use null in the oldValue field; The firePropertyChange() method only passes int, boolean and Object. So if you are not passing an int or boolean, you need to cast the value that was passed in the event on the receiving end.

like image 70
Johnny Avatar answered Oct 21 '22 15:10

Johnny