【问题标题】:How to modify the selected tableview according to the tableview cell如何根据tableview单元格修改选中的tableview
【发布时间】:2019-05-18 16:17:18
【问题描述】:

我在这里自定义了一个超链接单元格。我希望tableview在单击此链接时选择内容,但是添加超链接后,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

【问题讨论】:

  • 您可以在通过selection model 单击链接时以编程方式选择单元格。另外,要求用户双击超链接会不会有点不典型?通常链接是一个单击界面。注意Hyperlink 有一个onAction 属性。
  • 谢谢,在setOnMouseClicked中如何实现,有具体例子吗?

标签: javafx javafx-tableview


【解决方案1】:

当点击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 处理程序。

注意以上没有考虑多选模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2021-09-13
    • 2014-07-18
    • 2017-04-26
    • 2015-04-20
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多