JavaFX的绑定属性不成员控制 [英] JavaFX bind not property member to control
问题描述
想象我像一个POJO:
Imagine I have a POJO like:
public class Person()
{
private int id;
private String name;
public int getId()
{
return this.id;
}
public String getName()
{
return this.name;
}
}
如果我需要用bind()方法来名成员绑定到JavaFX的标签,我不能适用,因为我需要和观察的价值。
If I need to bind name member to JavaFX label using bind() method, I can't apply because I need and observable value.
我知道,我可以使用,而不是StringProperty字符串,但我需要的原始类型,因为我使用Hibernate,我不知道是否可以休眠,通过JavaFX支持的属性从DB地图数据。
I know that I can use StringProperty instead String, but I need primitive types because I use Hibernate and I don't know if Hibernate could support properties from JavaFX to map data from DB.
我有哪些替代从我的POJO绑定到一个JavaFX控制?
Which alternatives I have to bind from my pojo to a JavaFX control?
推荐答案
您有几个选择。
首先,它可以使用FX属性在JPA / Hibernate的实体,但你必须要小心一点。总之,你需要确保你使用的,而不是试图直接设置字段,这样的ORM调用get / set方法属性访问。史蒂芬面包车IMPE 讨论这个问题在他的博客一>,我也博客上同一主题的。有一件事我还没有尝试过在这里是映射集合,并使用 ObservableList
取值:作为JPA实现使用列表的子接口,可能会非常棘手
。
Firstly, it's possible to use FX Properties in JPA/Hibernate entities, though you have to be a little careful. In short, you need to make sure you use property access so that the ORM calls the get/set methods, instead of trying to set the field directly. Steven van Impe discusses this on his blog, and I also blogged on the same topic. One thing I haven't tried here is mapping collections and using ObservableList
s: that might be tricky as JPA implementations use a subinterface of List
.
您另一种选择是让在Java Bean的意义上的性能绑定属性,然后使用的 Java Bean的属性适配器:
Your other option is to make the properties "bound properties" in the Java Bean sense, and then to use a Java Bean Property Adapter:
import java.beans.PropertyChangeSupport ;
public class Person()
{
private int id;
private String name;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
public int getId()
{
return this.id;
}
public void setId(int id)
{
int oldId = this.id ;
this.id = id ;
pcs.firePropertyChange("id", oldId, id);
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
String oldName = this.name ;
this.name = name ;
pcs.firePropertyChange("name", oldName, name);
}
}
然后,你可以做
Label nameLabel = new Label();
Person person = new Person();
nameLabel.textProperty().bind(JavaBeanStringPropertyBuilder.create()
.bean(person)
.name("name") // name of property to bind to
.build());
这篇关于JavaFX的绑定属性不成员控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!