Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context Menu on a row of TableView?

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.

What I have...

In Scene Builder I have a method that runs on when the Context Menu is activated but that isn't exactly what I want. This would be fine really because I am programmatically grab the selected item from the table whenever I want. The issue, if I keep what I currently have, is getting the context menu to popup at the selected element.

contextMenu is the context menu with menu items. connectedUsers is the TableView

The following is the closest I can get, but this shows the context menu at the bottom of the TableView

contextMenu.show(connectedUsers, Side.BOTTOM, 0, 0);
like image 493
Michael Scott Avatar asked Jan 09 '14 00:01

Michael Scott


2 Answers

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

table.setRowFactory(
    new Callback<TableView<Person>, TableRow<Person>>() {
        @Override
        public TableRow<Person> call(TableView<Person> tableView) {
            final TableRow<Person> row = new TableRow<>();
            final ContextMenu rowMenu = new ContextMenu();
            MenuItem editItem = new MenuItem("Edit");
            editItem.setOnAction(...);
            MenuItem removeItem = new MenuItem("Delete");
            removeItem.setOnAction(new EventHandler<ActionEvent>() {
        
                @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((ContextMenu) null)
              .otherwise(rowMenu);
            return row;
    }
});
like image 103
Luca S. Avatar answered Sep 23 '22 14:09

Luca S.


JavaFX 8 (with Lambda):

MenuItem mi1 = new MenuItem("Menu item 1");
mi1.setOnAction((ActionEvent event) -> {
    System.out.println("Menu item 1");
    Object item = table.getSelectionModel().getSelectedItem();
    System.out.println("Selected item: " + item);
});

ContextMenu menu = new ContextMenu();
menu.getItems().add(mi1);
table.setContextMenu(menu);

See also: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ContextMenu.html

like image 17
ceklock Avatar answered Sep 21 '22 14:09

ceklock