开发者

Simple Question: ValueChanged Event in Java

开发者 https://www.devze.com 2023-02-18 03:57 出处:网络
Is there an event in Java that fires when a value changes? Like in this example public class Example{ public String v开发者_如何学JAVAar1 = \"Something\";

Is there an event in Java that fires when a value changes? Like in this example

public class Example{
    public String v开发者_如何学JAVAar1 = "Something";
    public Int var2 = 4;
}

If var1 or var2 their values change for whatever the event should fire.


The answer is not to expose your fields publicly to start with. Make the fields private, introduce getter and setter methods, and you can call whatever you like within the setter if the value's changed.

public class Example {
    private String var1 = "Something";

    public String getVar1() {
        return var1;
    }

    public void setVar1(String var1) {
        // TODO: null guards
        if (var1.equals(this.var1)) {
            // No-op - no need to do anything
            return;
        }
        this.var1 = var1;
        notifyListenersOfChangeToVar1();
    }
}


Check out the PropertyChangeListener http://download.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html


I think you might be looking for the "observer" design pattern (Wikipedia Entry)

This is implemented in java via extending Obserable and having objects that want to be notified implement the Observer interface.

0

精彩评论

暂无评论...
验证码 换一张
取 消