我有一个名为Passage的类,它包含一个名为Action的不可观测的类。Action包含一个SimpleStringProperty。
class Passage {
Action action = null;
Action getAction() { return action; }
void setAction(Action action) { this.action = action; }
boolean hasAction() { return action != null; }
}
class Action {
StringProperty myStringProperty = new SimpleStringProperty();
StringProperty getStringProperty() { return myStringProperty; }
// and other methods, many of which modify myStringProperty
}我想将该字符串属性绑定到UI标签。似乎这应该是一件很简单的事情:
label.textProperty.bind(passage.getAction().getStringProperty());但是,Action有时可能是空的。我试过以下几种方法:
label.textProperty.bind(passage.hasAction() ? passage.getAction().getStringProperty() : new SimpleStringProperty("") );然后,如果Action启动null (因此标签为空),然后将操作分配给非空(即调用setAction() ),则标签不会更新以反映更改。
我需要让人们注意我的行动吗?请参阅:Binding to javafx properties of a object that can be null
上面的解决方案使用的是一元操作,我对此并不熟悉。所以我读了一篇有用的博文:http://tomasmikula.github.io/blog/2014/03/26/monadic-operations-on-observablevalue.html
我尝试过使用EasyBind进行这个绑定。
我创建了一个新的类ObservableAction,它封装了一个Action,使它成为一个可观察的值(尽管我不确定我是否正确地完成了这个步骤):
import javafx.beans.binding.ObjectBinding;
public class ObservableAction extends ObjectBinding <Action>
{
private final Action value;
public ObservableAction(Action action) {
this.value = action;
}
@Override
public Action computeValue()
{
return value;
}
}然后,我的ViewController中有以下代码(同样,不确定我是否正确地完成了这一操作):
MonadicObservableValue<Action> monadicAction = EasyBind.monadic(new ObservableAction(passage.getAction()));
actionLabel.textProperty().bind(monadicAction.flatMap(action -> action.getTextProperty()).orElse(""));其结果与我以前所经历的一样:当Action不是null时,它可以很好地工作。但是,如果Action启动为null,然后变为非null,则不会更新标签。
发布于 2017-07-12 22:11:07
我建议在Passage中有一个将与action的属性绑定的属性。一旦设置了新的操作,就绑定它的属性,并且只使用Passage的属性。
class Passage {
private Action action;
private StringProperty actionMyStringProperty = new SimpleStringProperty();
void setAction(Action action) {
this.action = action;
// Unbind the previous binding if any (it is safe when nothing to unbind).
actionMyStringProperty.unbind();
if (action != null){
actionMyStringProperty.bind(action.getStringProperty());
}
}
public StringProperty actionMyStringProperty() {
return actionMyStringProperty;
}
}
class Action {
private StringProperty myStringProperty = new SimpleStringProperty();
StringProperty getStringProperty() {
return myStringProperty;
}
}在客户端:
label.textProperty.bind(passage.actionMyStringProperty());https://stackoverflow.com/questions/45062274
复制相似问题