TableView 中的 JavaFX 属性 [英] JavaFX Properties in TableView
问题描述
我正在自学如何在 TableView 中使用 JavaFX 属性,但在处理某些属性类型时遇到了问题.我有一个包含两个属性的对象 Person
I am teaching myself how to work with JavaFX properties within the TableView and am having trouble with some property types. I have an object Person that contains two properties
public class Person {
private final StringProperty firstName;
private final IntegerProperty age;
public Person(String firstName, Integer age) {
this.firstName = new SimpleStringProperty(firstName);
this.age = new SimpleIntegerProperty(age);
}
public Integer getAge() {
return age.get();
}
public void setAge(Integer age) {
this.age.set(age);
}
public IntegerProperty ageProperty() {
return age;
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
}
目标一旦创建就是在一个TableView中使用这个对象.我已经像这样创建了两个表格列.
Once created by goal is to use this object in a TableView. I've created the two table columns like this.
TableColumn<Person, String> firstNameColumn = new TableColumn<Person, String>("First Name");
TableColumn<Person, Integer> ageColumn = new TableColumn<Person, Integer>("Age");
然后我想使用 Lambda 表达式设置单元格值工厂.这就是问题出现的地方.StringProperty firstName 工作得很好.但是,IntegerProperty 给了我错误消息 "Type mismatch: cannot convert from IntegerProperty
to ObservableValue
"
I then want to set the cell value factory using Lambda expressions. This is where the problem arises. The StringProperty firstName works just fine. However, the IntegerProperty gives me the error message "Type mismatch: cannot convert from IntegerProperty
to ObservableValue<Integer>
"
firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
ageColumn.setCellValueFactory(cellData -> cellData.getValue().ageProperty());
谁能解释一下 ageColumn.setCellValueFactory(...) 出了什么问题?任何帮助将不胜感激.
Can anyone shed some light on what is going wrong with the ageColumn.setCellValueFactory(...)? Any help would be greatly appreciated.
谢谢!
推荐答案
属性 API 的一个有点奇怪的部分是 IntegerProperty
实现了 ObservableValue
,而不是 ObservableValue
.所以,有点违反直觉,你需要
One somewhat strange part of the property API is that IntegerProperty
implements ObservableValue<Number>
, not ObservableValue<Integer>
. So, somewhat counterintuitively, you need
TableColumn<Person, Number> ageColumn = new TableColumn<Person, Number>("Age");
顺便说一句,我不确定这是否会导致问题,但更常见的是使用 int
而不是 Integer
作为 get 方法的返回类型以及模型类中 set 方法的参数类型.这些匹配 IntegerProperty.get()
和 IntegerProperty.set(...)
的类型,因此它只是避免了一些隐式自动(取消)装箱.
As an aside, and I'm not sure if this causes problems, but it's more usual to use int
instead of Integer
for the return type for the get method and the parameter type for the set method in your model class. These match the types for IntegerProperty.get()
and IntegerProperty.set(...)
, so it just avoids some implicit auto (un)boxing.
这篇关于TableView 中的 JavaFX 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!