因此在课堂上我们总是使用以下语法。如果我错了,请纠正我,但这是一个bean,因为它使用getter / setter。它有一个nullary构造函数,类实现了serializable。
// option 1
private int customerID ;
public CustomerDTO ()
{
this(0);
}
public CustomerDTO(int customerID) {
setCustomerID(customerID);
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public int getCustomerID() {
return customerID;
}
但是今天我遇到了类似的东西。我需要导入
import javafx.beans.property.SimpleStringProperty;
但是选项1和2之间的主要区别是什么。 我什么时候应该使用选项1或选项2 哪一个更好或者取决于具体情况。
// option 2
private final IntegerProperty customerID;
public CustomerDTO ()
{
this(null);
}
public CustomerDTO(IntegerProperty customerID) {
this.customerID = new SimpleIntegerProperty();
}
public IntegerProperty getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID.set(customerID);
}
答案 0 :(得分:0)
在构建JavaFX应用程序并希望将模型与gui绑定时,使用选项2。
示例:
public class Foo {
private final StringProperty foo = new SimpleStringProperty();
public String getFoo() {
return foo.get();
}
public StringProperty fooProperty() {
return foo;
}
public void setFoo(String foo) {
this.foo.set(foo);
}
}
public class FooController {
@FXML
private TextField fooTextField;
private final Foo foo = new Foo();
@FXML
public void initialize() {
foo.fooProperty().bindBidirectional(fooTextField.textProperty());
}
}
答案 1 :(得分:0)
public CustomerDTO(IntegerProperty customerID) {
毫无意义,property
是一个final
类成员,它封装了一个value
,这个值可以通过setter设置并通过setter获取,在JavaFX中在您的情况下,建议您为ReadOnlyObjectProperty或ReadOnlyIntegerProperty实现getter,这可以通过ReadOnlyIntegerWrapper及其getReadOnlyProperty方法完成。这使得开发者能够绑定来自其他类的值,同时确保值随时存在,JavaFX Bindings是一种非常优雅且面向对象的数据封装方法。
您的"选项2"实际上是有缺陷的,因为它允许属性重新定义,这打破了这个概念并使属性本身无用。除了无法重新定义属性本身外,它还会破坏GUI功能,请参阅接受的答案