所以我有一个正常工作的表并从 ObservableList
中获取数据使用此处的代码:
public void setMainTableData(ObservableList<FileMP3> list)
{
artistCol.setCellValueFactory(new PropertyValueFactory<FileMP3, String>("artist"));
albumCol.setCellValueFactory(new PropertyValueFactory<FileMP3, String>("album"));
titleCol.setCellValueFactory(new PropertyValueFactory<FileMP3, String>("title"));
trackCol.setCellValueFactory(new PropertyValueFactory<FileMP3, String>("track"));
yearCol.setCellValueFactory(new PropertyValueFactory<FileMP3, String>("year"));
mainTable.setItems(list);
}
但这些列并不都包含字符串数据 - 我需要能够插入 int
,以及可能的其他类型,如 Duration
. track
和 year
条目存储为整数,并且有一个(未显示)条目称为 length
.这存储在我的 FileMP3
中对象作为 Duration
,并且在将数据插入表之前,我没有看到任何明显的方法来操作存储在那里的数据。我希望能够使用 Duration.getMillis()
然后对其进行一些数学计算,使其成为可显示的 int
格式,但我想将其存储在 FileMP3
中作为Duration
.
我读过的所有关于该主题的教程都使用构造函数:
new PropertyValueFactory<FileMP3, String>("genre")
总而言之,我希望能够插入 String
以外的内容放入表中。
最佳答案
您可以将 String 替换为任何(引用,而非原始)类型。例如:
TableColumn<FileMP3, Integer> yearCol = new TableColumn<>("Year");
yearCol.setCellValueFatory(new PropertyValueFactory<FileMP3, Integer>("year"));
与持续时间(而不是整数)类似。
默认情况下,将通过对单元格中的值调用 toString() 来显示单元格中的值。如果您希望值以不同方式显示,您可以创建一个自定义单元格工厂(不同于单元格值工厂):
TableColumn<FileMP3, Integer> durationCol = new TableColumn<>("Duration");
durationCol.setCellValueFactory(new PropertyValueFactory<FileMP3, Duration>("duration"));
durationCol.setCellFactory(new Callback<TableColumn<FileMP3, Duration>, TableCell<FileMP3, Duration>>() {
@Override
public TableCell<FileMP3, Duration> call(TableColumn<FileMP3, Duration> col) {
return new TableCell<FileMP3, Duration>() {
@Override
protected void updateItem(Duration duration, boolean empty) {
super.updateItem(duration, empty);
if (empty) {
setText(null);
} else {
setText(Double.toString(duration.toMillis());
}
}
};
}
});
关于java - 将整数(非字符串)数据插入 JavaFX2 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556805/