Constantly check for changes in Java?

How can I check a logical change in state over a certain period of time, and if a change is made during this period of time, execute the method?

Can any help be provided in Java.

Thank.

+5
source share
4 answers

It looks like you want to wrap a boolean in a class that you can listen for changes.

class ObservableBoolean {

    // "CopyOnWrite" to avoid concurrent modification exceptions in loop below.
    private final List<ChangeListener> listeners =
            new CopyOnWriteArrayList<ChangeListener>();

    private boolean value;

    public boolean getValue() {
        return value;
    }

    public synchronized void setValue(boolean b) {
        value = b;
        for (ChangeListener cl : listeners)
            cl.stateChanged(new ChangeEvent(this));
    }

    public synchronized void addChangeListener(ChangeListener cl) {
        listeners.add(cl);
    }

    public synchronized void removeChangeListener(ChangeListener cl) {
        listeners.remove(cl);
    }
}

Then just do:

ObservableBoolean b = new ObservableBoolean();

//...

// Start the "period of time":
b.addChangeListener(iWantToBeNotifiedOfChanges);

// ...

// End the "period of time":
b.removeChangeListener(iWantToBeNotifiedOfChanges);

This is actually a simple example of an MVC pattern (and an observer pattern). The model in this case is ObservableBoolean, and the view will be a "view" that wants to receive notification of changes.

ChangeListener, javax.swing... import

+15

- -...

public class Bool
{
    public Bool(){ _val = false; }
    public Bool(boolean val) { _val = val; }

    public boolean getValue(){ return _val; }
    public void setValue(boolean val){ 
         _changesupport.firePropertyChange("value",_val,_val=val);
    }

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

    public void removePropertyChangeListener(PropertyChangeListener listener){
        _changesupport.removePropertyChangeListener( listener );
    }

    private boolean _val = false;
    private final PropertyChangeSupport _changesupport = new PropertyChangeSupport(this);
}

Swing, PropertyChangeSupport, , . PropertyChangeListener PropertyChangeEvent.

+6

Timer , Thread.

.

edit: , . , - , . . - . , , Timer .

example: ( -) 5 , (reques = true). . Immediatelly update (, Tribal Wars ) .

+1

It sounds like you should take a look at some sort of implementation Model View Controller Pattern. Look here

The main idea is that you should fire the event when the logical state changes, and then this event fires, your listener should handle this.

-2
source

All Articles