How to modify the selected tableview according to the tableview cell

205 views Asked by At

I have customized a Hyperlink cell here. I want the tableview to select the content when I click this link, but after I add Hyperlink, the tableview's selected seems to be invalid.

        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

If the cell is not selected, a null exception will be reported when the following code is used.

                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();

The effect you want to achieve is as follows

Rendering

1

There are 1 answers

0
Slaw On

You can manually select the cell, using the table's selection model, when the Hyperlink is clicked on.

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

I used the onAction property which will be fired when the Hyperlink has been clicked once. This is typical behavior for a hyperlink, but if you want to only perform the action on a double-click then you can keep using your onMouseClicked handler.

Note the above does not take into account multiple-selection mode.