JavaFX bind not property member to control

后端 未结 1 1743
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 17:29

Imagine I have a POJO like:

public class Person()
{
  private int id;
  private String name;

  public int getId()
  {
     return this.id;
  }

  public Str         


        
相关标签:
1条回答
  • 2021-01-15 18:09

    You have a couple of options here.

    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 ObservableLists: that might be tricky as JPA implementations use a subinterface of List.

    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);
        }
    }
    

    Then you can do

    Label nameLabel = new Label();
    Person person = new Person();
    nameLabel.textProperty().bind(JavaBeanStringPropertyBuilder.create()
        .bean(person)
        .name("name") // name of property to bind to
        .build());
    
    0 讨论(0)
提交回复
热议问题