gpt4 book ai didi

java - 如何在模型类中使用集合类型作为 javafx.beans.property

转载 作者:行者123 更新时间:2023-12-01 22:09:59 25 4
gpt4 key购买 nike

我一直在编写我的第一个 javafx 应用程序。有几个模型类。我像往常一样描述了实体类。 F.e:

class Person {
private String firstName;
private String lastName;

// getters and setters bellow.....
}

我遇到了一个article作者建议对模型类的所有字段使用 Properties。例如:

public class NewPerson {

private final StringProperty firstName;
private final StringProperty lastName;
public String getFirstName() {
return firstName.get();
}

public void setFirstName(String firstName) {
this.firstName.set(firstName);
}

public StringProperty firstNameProperty() {
return firstName;
}

public String getLastName() {
return lastName.get();
}

public void setLastName(String lastName) {
this.lastName.set(lastName);
}

public StringProperty lastNameProperty() {
return lastName;
} }

这个效果很好!但是我怎样才能以 Properties 的方式使用 java.util.Collections 呢?我应该如何“包裹”它们? F.e.我想使用:

// set of user's certificates
private Set<Certificate> certificates;

它作为 NewPerson 类中的属性会如何?

最佳答案

这取决于您希望 API 是什么样子。最简单的版本是:

public class User {

private final ObservableSet<Certificate> certificates = FXCollections.observableSet();

public ObservableSet<Certificate> getCertificates() {
return certificates ;
}

// other properties...
}

这允许相当多的功能:

User user = new User();

user.getCertificates().addListener((SetChangeListener.Change<? extends Certificate> change) -> {
if (change.wasAdded()) {
// ...
}
if (change.wasRemoved()) {
// ...
}
});

Set<Certificate> someCertificates = ... ;
user.getCertificates().setAll(someCertificates);
user.getCertificates().add(new Certificate());

ObservableSet<Certificate> anotherSet = ... ;
Bindings.bindContent(user.getCertificates(), anotherSet);
// etc...

唯一不允许的是您从外部插入您自己的设置实现。 IE。你做不到

User user = new User();
ObservableSet<Certificate> certificates = ... ;
user.setCertificates(certificates);

请注意,这只是与

真正不同
user.getCertificates().setAll(certificates);

如果您有 ObservableSet 的具体实现您想要使用的,或者如果您有一个模型类已经包含 ObservableSet<Certificate> (在后一种情况下,您仍然可以考虑 Bindings.bindContentBidirectional(user.getCertificates(), certificates) )。如果您确实需要 setCertificates(...) API,然后创建SetProperty<Certificate> :

public class User {

private final SetProperty<Certificate> certificates
= new SimpleSetProperty<>(FXCollections.observableSet());

public final ObservableSet<Certificate> getCertificates() {
return certificatesProperty().get();
}

public final void setCertificate(ObservableSet<Certificate> certificates) {
certificatesProperty().set(certificates);
}

public SetProperty<Certificate> certificatesProperty() {
return certificates ;
}

// other properties....
}

关于java - 如何在模型类中使用集合类型作为 javafx.beans.property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32005917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com