何时在String上使用StringProperty?

Nat*_*ara 16 string binding javafx

我正在JavaFX中开发一个应用程序,我希望在单个Person类中表示Person的信息.我遇到了一个教程,其中一个人的名字被表示为StringProperty代替String.我已经搜索了这些的不同之处并发现了这个这个但是解释并不足以让我抓住这个概念.网上的一些帖子表示使用StringProperty结束有优势String但却无法提及.

现在的问题是:什么样的条件需要一个使用StringPropertyString,什么是这样做的优势是什么?

为什么这个:

StringProperty firstName;

在此:

String firstName;

Ulu*_*Biy 13

何时使用StringProperty firstName over String firstName?

firstName其他人观察到这个变量时使用它.你也可以通过附加一个监听器来观察它.您可以在与JavaFX的其他可观察对象的绑定中使用此变量.在某些情况下,必须使用JavaFX属性,例如使用可编辑的tableView呈现的Person列表.要在编辑的单元格中立即反映更改,基础边界字段应为属性.


aw-*_*ink 8

JavaFX尝试启用MVC模式.应使用"属性"创建模型以利用"绑定".在您的情况下,Model是Person类,因此您只需添加StringProperty firstName即可.但是在JavaFX中,你必须处理其他命名约定,就像Pojo Bean中的简单getter和setter一样.

JavaFX中属性的命名约定是:

 public class Person {
     private StringProperty firstName;
     public void setFirstName(String value) { firstNameProperty().set(value); }
     public String getFirstName() { return firstNameProperty().get(); }
     public StringProperty firstNameProperty() { 
         if (firstName == null) firstName = new SimpleStringProperty(this, "firstName");
         return firstName; 
     }

     private StringProperty lastName;
     public void setLastName(String value) { lastNameProperty().set(value); }
     public String getLastName() { return lastNameProperty().get(); }
     public StringProperty lastNameProperty() { 
         if (lastName == null) lastName = new SimpleStringProperty(this, "lastName");
         return lastName; 
     } 
 }
Run Code Online (Sandbox Code Playgroud)

之后,您可以将TableView的TableColumn绑定到属性"lastName"

TableView<Person> table = new TableView<Person>();

ObservableList<Person> teamMembers = getTeamMembers();
table.setItems(teamMembers);

TableColumn<Person,String> lastNameCol = new TableColumn<Person,String>("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));
Run Code Online (Sandbox Code Playgroud)

没有属性,这将是更多的代码,您将没有实现ChangeListener/InvalidationListener支持的优势.

上面的示例来自JavaFX TableView

因此,为Ja​​vaFX创建Model的推荐方法是使用JavaFX-Properties而不是类型的内置.