将整数(非String)数据插入JavaFX2 TableView

时间:2013-12-13 00:08:25

标签: java javafx javafx-2 tableview

所以我有一张桌子正常工作,并使用以下代码从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,还可能插入其他类型的Durationtrackyear条目存储为整数,并且有一个名为length的(未显示)条目。它作为FileMP3存储在我的Duration对象中,在将其插入表中之前,我没有看到任何明显的方法来操作存储在那里的数据。我希望能够使用Duration.getMillis(),然后对其进行一些数学计算以使其成为可显示的int格式,但我希望将其保存在FileMP3中{ {1}}。

我在这个主题上阅读的所有教程都使用构造函数:

Duration

总而言之,我希望能够在表格中插入除new PropertyValueFactory<FileMP3, String>("genre")之外的其他内容。

2 个答案:

答案 0 :(得分:4)

您可以使用任何(引用,而不是原始)类型替换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());
                }
            }
        };
    }
});

答案 1 :(得分:1)

您可以提供自定义单元格值工厂:

duration.setCellValueFactory(new Callback<CellDataFeatures<FileMP3, Integer>, ObservableValue<Integer>>() {
    @Override public ObservableValue<Integer> call(CellDataFeatures<FileMP3, Integer> c) {
        return new SimpleIntegerProperty(c.getValue().getDurationAsInt()));
    }
});