如何根据表格视图单元格修改选定的表格视图

时间:2019-05-18 16:17:19

标签: javafx javafx-tableview

我在这里自定义了一个超链接单元。单击此链接时,我希望Tableview选择内容,但是在添加Hyperlink之后,选择的Tableview似乎无效。

        tb_uGoodUrl.setCellFactory(new Callback<TableColumn<GoodModel, String>, TableCell<GoodModel, String>>() {
        @Override
        public TableCell<GoodModel, String> call(TableColumn<GoodModel, String> param) {
            TableCell<GoodModel, String> cell = new TableCell<GoodModel, String>() {
                private final Hyperlink hyperlink = new Hyperlink();
                {
                    hyperlink.setOnMouseClicked(event -> {
                        if(event.getClickCount()  == 2){
                            String url = getItem();
                            hostServices.showDocument(url);
                        }
                    });
                }

                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setGraphic(null);
                    }else {
                        hyperlink.setText(getItem());
                        setGraphic(hyperlink);
                    }
                }
            };
            return cell;
        }
    });

Click on the link, the cell is not selected

如果未选中该单元格,则在使用以下代码时将报告空异常。

                TablePosition pos = tableView.getSelectionModel().getSelectedCells().get(0);
            int row = pos.getRow();
            // Item here is the table view type:
            GoodModel item = tableView.getItems().get(row);
            TableColumn col = pos.getTableColumn();
            // this gives the value in the selected cell:
            String data = (String) col.getCellObservableValue(item).getValue();

您想要实现的效果如下

Rendering

1 个答案:

答案 0 :(得分:0)

单击Hyperlink时,您可以使用table's selection model手动选择单元格。

// Assuming this code is inside a TableCell implementation
hyperlink.setOnAction(event -> {
    event.consume();
    getTableView().getSelectionModel().select(getIndex(), getTableColumn());
    // show your document
});

我使用了onAction属性,该属性将在一次单击Hyperlink时触发。这是超链接的典型行为,但是如果您只想双击执行操作,则可以继续使用onMouseClicked处理程序。

请注意,以上内容并未考虑多选模式。