如何使复杂对象成为Observable

时间:2017-02-07 06:56:06

标签: java javafx observable

我有多个JavaFX窗格和画布,它们使用所需的数据引用复杂对象,我希望它们在对象更改时重绘。

这会调用对象是Observable,但我会使用哪个类? JavaFX似乎主要有ObservableValue子类,它包装一个值并允许交换它。我不想换掉复杂的对象,只是在发生变化时通知听众。我可以通过实施addListener来做到这一点,但我确定已经为我做了一个子类。

class ComplexObject /* extends SomeObservableClass */ {
    public int getValue1 { complex calculations... };
    public int getValue2 { ... };

    public void setNewValue1(int newValue) { ... }
}

class ComplexRenderer extends Canvas implements InvalidationListener {
    private ComplexObject complexObject;

    public void setComplexObject(ComplexObject complexObject) {
        this.complexObject = complexObject;
        complexObject.addListener(this);
    }

    public void draw() { ... }
}

ComplexObject应该扩展哪个类?是否存在维护侦听器列表并具有类似fireValueChangedEvent()的内容,以便我可以通知所有侦听器?

我在JavaFX中看到的所有东西似乎都是针对属性的,这在这里似乎不是正确的选择。

2 个答案:

答案 0 :(得分:3)

不确定你交换意味着什么,而且不确定我是否理解你。

class ComplexObject {
    private IntegerProperty value1 = new SimpleIntegerProperty();
    private IntegerProperty value2 = new SimpleIntegerProperty();
    private BooleanProperty internalChanged = new SimpleBooleanProperty(false);

    public ComplexObject() {
        this.internalChanged.bind(Bindings.createBooleanBinding(() ->
            this.internalChanged.set(!this.internalChanged.get()), this.value1, this.value2));
    }

    public IntegerProperty value1Property() { return this.value1; }
    public int getValue1() { return this.value1.get(); }
    public void setValue1(int value) { return this.value1.set(value); }

    public IntegerProperty value2Property() { return this.value2; }
    public int getValue2() { return this.value2.get(); }
    public void setValue2(int value) { return this.value2.set(value); }

    public void setNewValue1(int newValue) { /* What value is this??? */ }

    public BooleanProperty internalChangedProperty() { return this.internalChanged; }
}

class ComplexRenderer extends Canvas implements InvalidationListener {
    private ComplexObject complexObject;

    public void setComplexObject(ComplexObject complexObject) {
        this.complexObject = complexObject;
        complexObject.internalChangedProperty().addListener(this);
    }
    @Override public void invalidated(Observable observable) {
        // Something inside complex object changed
    }

    public void draw() { ... }
}

答案 1 :(得分:0)

也许您可以查看界面ObjectPropertyBase<T>以及实现ObjectPropertyBase<T>的课程SimpleObjectProperty<T>Observable

但是,您必须定义对象何时更改和侦听逻辑。

对不起,这只是一些工作,但我希望它可能有用。