Java PropertyChangeListener

Posted by Laphroaig on Stack Overflow See other posts from Stack Overflow or by Laphroaig
Published on 2011-02-13T22:51:51Z Indexed on 2011/02/13 23:25 UTC
Read the original article Hit count: 136

Hi, i'm trying to figure out how to listen a property change on another class. this is my code:

class with the property to listen:

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

class where i need to know when 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). Sorry if it can be a stupid question, i'm learning now java and can't find a solution.

© Stack Overflow or respective owner

Related posts about java

Related posts about propertychangelistener