How can I right click on a cell in tableview in Javafx (fxml)?

為{幸葍}努か 提交于 2019-12-18 09:01:25

问题


I am programming a table view with JavaFX and fxml. I want to do some actions when a user right clicks on a cell in the table. How can I do that? Is it possible to create a right click menu over a cell?

Thanks!


回答1:


Implement a cell factory for the table column(s) of interest. Create a cell in the cell factory and register the mouse listener with the cell.

Referring to the standard table example you can do something like

firstNameCol.setCellFactory(new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
    @Override
    public TableCell<Person, String> call(TableColumn<Person, String> col) {
        final TableCell<Person, String> cell = new TableCell<>();
        cell.textProperty().bind(cell.itemProperty()); // in general might need to subclass TableCell and override updateItem(...) here
        cell.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if (event.getButton == MouseButton.SECONDARY) {
                    // handle right click on cell...
                    // access cell data with cell.getItem();
                    // access row data with (Person)cell.getTableRow().getItem();
                }
            }
        });
        return cell ;
    }
});


来源:https://stackoverflow.com/questions/24140954/how-can-i-right-click-on-a-cell-in-tableview-in-javafx-fxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!