Context Menu on a row of TableView?

后端 未结 3 1803
北荒
北荒 2021-02-05 18:46

I am using JavaFX and my application has a table and I can add elements to the table but I want to create a context menu that displays on a row when I right click on that row.

3条回答
  •  一整个雨季
    2021-02-05 18:55

    I believe that the best solution would be this as discussed in here.

    table.setRowFactory(
        new Callback, TableRow>() {
            @Override
            public TableRow call(TableView tableView) {
                final TableRow row = new TableRow<>();
                final ContextMenu rowMenu = new ContextMenu();
                MenuItem editItem = new MenuItem("Edit");
                editItem.setOnAction(...);
                MenuItem removeItem = new MenuItem("Delete");
                removeItem.setOnAction(new EventHandler() {
    
                    @Override
                    public void handle(ActionEvent event) {
                        table.getItems().remove(row.getItem());
                    }
                });
                rowMenu.getItems().addAll(editItem, removeItem);
    
                // only display context menu for non-empty rows:
                row.contextMenuProperty().bind(
                  Bindings.when(row.emptyProperty())
                  .then(rowMenu)
                  .otherwise((ContextMenu)null));
                return row;
        }
    });
    

提交回复
热议问题