TableView - 如何在其中添加下载按钮

时间:2016-04-13 20:56:53

标签: java javafx download tableview

我想知道如何在JavaFX GUI中的tablew视图列中添加下载按钮,因此对于每个元素,我都可以访问链接并下载我需要的文件。 enter image description here

例如,在上图中,对于每一行,在下载列中,我想要一个下载按钮。

1 个答案:

答案 0 :(得分:1)

您需要为TableColumn提供Cell FactoryCell Value Factory。 cellFactory负责渲染从cellValueFactory获取的数据。

TableColumn<YourDataModel, String> yourColumn = new TableColumn<>();
yourColumn.setCellFactory(tableColumn -> new DownloadCell());
yourColumn.setCellValueFactory(cellData -> cellData.getValue().downloadProperty());

public class YourDataModel {

    private StringProperty download = new SimpleStringProperty();
    // additional fields

    public StringProperty downloadProperty() {
        return download;
    }

    public String getDownload() {
        return download.get();
    }

    public void setDownload(String value) {
        download.set(value);
    }

}

public class DownloadCell extends TableCell<YourDataModel, String> {

    private Hyperlink downloadLink;

    public DownloadCell() {
        downloadLink = new Hyperlink();
        downloadLink.setOnAction(evt -> {
            try {
                Desktop.getDesktop().browse(new URI(downloadLink.getText()));
            } catch (Exception e) {
                // exception handling
            }
        });
    }

    @Override
    protected void updateItem(String link, boolean empty) {
        super.updateItem(link, empty);

        if (link == null || empty) {
            setGraphic(null);
        } else {
            downloadLink.setText(link);
            setGraphic(downloadLink);
        }
    }
}