我正在尝试使用 JavaFX 中的 TableView 访问子类中的 getter 属性。我有以下课程:
public class PersonType implements Serializable {
private static final long serialVersionUID = 1L;
Person person;
short count;
public PersonType() {
}
public PersonType(Person person, short count) {
super();
this.person = person;
this.count = count;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public short getCount() {
return count;
}
public void setCount(short count) {
this.count = count;
}
Person 是这样的: public class Person implements Serializable {
private static final long serialVersionUID = 1L;
String firstName;
String lastName;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
好的 - 最后我们有以下内容:
@FXML
private TableColumn tcFirstName;
@FXML
private TableColumn tcLastName;
@FXML
private TableView tblPersonTypes;
ArrayList<PersonType> pType = new ArrayList<PersonType>();
//Can assume that pType here has say 5 entries, the point of this
//is I'm trying to get to the firstName, lastName properties of the
//PersonType in the TableView below like the following:
tcFirstName.setCellValueFactory(new PropertyValueFactory<String,String>("firstName"));
tcLastName.setCellValueFactory(new PropertyValueFactory<String,String>("lastName"));
//Populate Table with Card Records
ObservableList<PersonType> data = FXCollections.observableArrayList(pType);
tblPersonTypes.setItems(data);
而且我不确定如何使用 PersonTypes 列表告诉表格列我想要其中包含的 Person 对象的 firstName 和 lastName 属性。我知道我可以创建一个新对象,并从 PersonTypes 中获得“计数”,然后是“firstName”、“lastName”等的其他属性,而无需 Person 的对象属性。任何帮助将不胜感激。
- 编辑 -
我认为执行此操作的另一种方法是使用 CellFactories - 我将在其中将 Person 对象传递给 CellValueFactories,然后将 CellFactory 设置为返回一个字符串值(名字列的 firstName 等)。它看起来像这样:
tcFirstName.setCellValueFactory(new PropertyValueFactory<Person,String>("person"));
tcFirstName.setCellFactory(new Callback<TableColumn<Person,String>,TableCell<Person,String>>(){
@Override
public TableCell<Person,String> call(TableColumn<Person,String> param) {
TableCell<Person,String> cell = new TableCell<Person,String>(){
@Override
public void updateItem(String item, boolean empty) {
if(item!=null){
setGraphic(new Label(item.getFirstName()));
}
}
};
return cell;
}
});