JavaFX - 如何在tableview中引用单元的邻居

时间:2017-05-19 20:23:03

标签: button javafx tableview tablerow tablecell

我正在努力在JavaFX中创建一个包含可编辑属性的表。我希望能够开始编辑,提交更改,并使用将包含在每行中的按钮取消;但是,我在参考我想要开始编辑的单元格时遇到了一些困难。理想情况下,我想做类似的事情:

controller.buttonColumn.setCellFactory(p -> new TableCell<TableItem, String>(){
            @Override
            protected void updateItem(String s, boolean empty) {
                super.updateItem(s, empty);
                if (getTableRow().getItem()==null){
                    setGraphic(null);
                    return;
                }
                Button editButton = new Button("Edit");
                editButton.setOnAction(event -> {
                    getTableRow().getCell(1).startEdit();
                });
                setGraphic(editButton);

        });

这不起作用,因为TableRow没有访问特定单元格的方法。同样,我可以使用这样的一行:

getTableView()getEditingCell()的CancelEdit();

对于我的取消按钮,但getEditingCell()方法不返回TableCell,而是返回TablePosition,后者没有访问相应单元格的方法。

TL;博士 鉴于它的邻居,我正在寻找一种方法来访问TableView中的单元格。

1 个答案:

答案 0 :(得分:1)

您可以使用TableView.edit(int row, TableColumn<S,?> column) method

controller.buttonColumn.setCellFactory(p -> new TableCell<TableItem, String>(){
    @Override
    protected void updateItem(String s, boolean empty) {
        super.updateItem(s, empty);
        if (getTableRow().getItem()==null){
            setGraphic(null);
            return;
        }
        Button editButton = new Button("Edit");
        editButton.setOnAction(event -> {
            getTableView().edit(getIndex(), someTableColumn);
        });
        setGraphic(editButton);
    }
});

其中someTableColumn是包含您要开始编辑的单元格的列。

您可以使用相同的方法取消编辑:

tableView.edit(-1, null);