![](/img/trans.png)
[英]Why IntegerProperty implements Property<Number> and not Property<Integer>?
[英]what is IntegerProperty and why does it need to be imported
因此,在课堂上我们总是使用以下语法。 如果我错了,请纠正我,但这是一个bean,因为它使用getters / setters类。 它具有一个null构造函数,并且该类实现可序列化。
// 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);
}
在构建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());
}
}
public CustomerDTO(IntegerProperty customerID) {
毫无意义, property
是封装value
的final
类成员,可以通过setter设置此值,并通过setter获取,在JavaFX控制器类中,建议也为ReadOnlyObjectProperty实现getter或ReadOnlyIntegerProperty ,可以通过ReadOnlyIntegerWrapper及其getReadOnlyProperty方法来完成。 这使开发人员可以绑定到其他类的值,同时还可以确保该值随时存在,JavaFX 绑定是一种非常优雅且面向对象的数据封装方法。
您的“选项2”实际上是有缺陷的,因为它允许重新定义属性,这打破了这个概念并使属性本身变得无用。 它还会破坏GUI功能,除非无法重新定义属性本身,请参见接受的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.