我用于DTO POJOS。对于桌面客户端GUI,我使用JavaFX。当然,我想要双向(不是单声道!)数据绑定。我找到了两个解决方案:
1)使用特殊类Adapters。例如,如果我们有POJO类Person,那么我们创建JavaFx(* property)类PersonAdapter。除了在POJO Person中我们添加了PropertyChangeSupport。这种方法有效,但每个DTO都需要写DTOAdapter。 - 不好。
2)我发现了这篇文章https://ugate.wordpress.com/2012/06/14/javafx-programmatic-pojo-bindings/和javafx8 https://github.com/JFXtras/jfxtras-labs/blob/8.0/src/main/java/jfxtras/labs/scene/control/BeanPathAdapter.java的代码。说实话,我不明白他们如何知道POJO是否有所改变。换句话说,如果javafx改变 - POJO改变它很清楚。但是如果POJO改变了吗?我想到并决定试验的一些谜团
class Person{
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
测试代码:
Person person=new Person();
SimpleStringProperty sp=new SimpleStringProperty();
BeanPathAdapter<Person> testPA = new BeanPathAdapter<>(person);
testPA.bindBidirectional("name", sp);
person.setName("Name1");
System.out.println("Test1:"+sp.get());
sp.set("Name2");
System.out.println("Test2:"+test.getName()
结果如下:
Test1:null
Test2:Name2
所以我们看到方向javafx属性 - &gt; pojo工作。但是,pojo-> javafx属性没有。或者我做错了什么,或者它不起作用?也许有人会提出更好的解决方案?
答案 0 :(得分:0)
不幸的是,它确实起作用了。 bindBidirectional并不修改bean以便监听它的变化。您可能会混淆name bindBidirectional。这可以解释为它绑定双向属性(在您的示例中为sp)和 BeanPathAdapter 内部属性。 javafx - &gt;适配器(以及包裹的bean)和适配器 - &gt; javafx用你的意思。
因此,bean的更改不会影响适配器和绑定属性。但是如何在不改变属性和bean的情况下更改适配器?通过更改绑定到相同bean属性的另一个属性。例如:
Person person = new Person();
SimpleStringProperty firstProperty = new SimpleStringProperty();
SimpleStringProperty secondProperty = new SimpleStringProperty();
BeanPathAdapter<Person> testPA = new BeanPathAdapter<>(person);
testPA.bindBidirectional("name", firstProperty);
testPA.bindBidirectional("name", secondProperty);
firstProperty.set("fromFirst");
System.out.println("first:" + firstProperty.get() + " second=" + secondProperty.get() + " bean=" + person.getName());
secondProperty.set("fromSecond");
System.out.println("first:" + firstProperty.get() + " second=" + secondProperty.get() + " bean=" + person.getName());
person.setName("fromBean");
System.out.println("first:" + firstProperty.get() + " second=" + secondProperty.get() + " bean=" + person.getName());
结果如下:
first:fromFirst second=fromFirst bean=fromFirst
first:fromSecond second=fromSecond bean=fromSecond
first:fromSecond second=fromSecond bean=fromBean
但您可以通过添加testPA.setBean(person)强制更新属性;每次更改bean之后都要处理。