我读过这篇文章: http://code.makery.ch/blog/javafx-8-tableview-sorting-filtering/ 但是我对包含Long值而不是String的列有问题。
@FXML
private TableView<Person> personTable;
@FXML
private TableColumn<Person, String> firstNameColumn;
@FXML
private TableColumn<Person, Long> lastNameColumn;
@FXML
private void initialize() {
// 0. Initialize the columns.
firstNameColumn.setCellValueFactory((TableColumn.CellDataFeatures<Person, String> cellData) -> {
return cellData.getValue().firstNameProperty();
});
firstNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, String>,
ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Person, String> param) {
return new SimpleStringProperty("str"); // HERE IS OK
}
});
lastNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, Long>, ObservableValue<Long>>() {
@Override
public ObservableValue<Long> call(TableColumn.CellDataFeatures<Person, Long> param) {
return new SimpleLongProperty(14L); // HERE IS WRONG
// Incompatible types.
// Required: ObservableValue<java.lang.Long>
// Found: SimpleLongProperty
}
});
@FXML
private TableView<Person> personTable;
@FXML
private TableColumn<Person, String> firstNameColumn;
@FXML
private TableColumn<Person, Long> lastNameColumn;
@FXML
private void initialize() {
// 0. Initialize the columns.
firstNameColumn.setCellValueFactory((TableColumn.CellDataFeatures<Person, String> cellData) -> {
return cellData.getValue().firstNameProperty();
});
firstNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, String>,
ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Person, String> param) {
return new SimpleStringProperty("str"); // HERE IS OK
}
});
lastNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, Long>, ObservableValue<Long>>() {
@Override
public ObservableValue<Long> call(TableColumn.CellDataFeatures<Person, Long> param) {
return new SimpleLongProperty(14L); // HERE IS WRONG
// Incompatible types.
// Required: ObservableValue<java.lang.Long>
// Found: SimpleLongProperty
}
});
我在代码中写入错误。
任何人都知道,我做错了什么?
感谢。
答案 0 :(得分:1)
有些违反直觉,LongProperty
实施ObservableValue<Number>
,而不是ObservableValue<Long>
。如果适合您的要求,最简单的解决方法是让您的TableColumn
类型Number
:
@FXML
private TableColumn<Person, Number> lastNameColumn;
lastNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, Number>, ObservableValue<Number>>() {
@Override
public ObservableValue<Number> call(TableColumn.CellDataFeatures<Person, Number> param) {
return new SimpleLongProperty(14L);
}
});
如果您确实需要列类型为Long
,则需要执行
lastNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, Long>, ObservableValue<Long>>() {
@Override
public ObservableValue<Long> call(TableColumn.CellDataFeatures<Person, Long> param) {
return new SimpleObjectProperty<Long>(14L);
}
});