Context menu in tableview row?

I use JavaFX, and my application has a table, and I can add items to the table, but I want to create a context menu that appears in the row when I right-click on this row.

What have I got ...

In Scene Builder, I have a method that works when the context menu is activated, but this is not quite what I want. That would be good, because I programmatically grab the selected item from the table whenever I want. The problem is, if I save what I have, it brings up a context menu for the selected item.

contextMenu is a context menu with menu items. connectedUsers - TableView

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

contextMenu.show(connectedUsers, Side.BOTTOM, 0, 0); 
+11
java javafx contextmenu
source share
3 answers

try it.

 ContextMenu cm = new ContextMenu(); MenuItem mi1 = new MenuItem("Menu 1"); cm.getItems().add(mi1); MenuItem mi2 = new MenuItem("Menu 2"); cm.getItems().add(mi2); table.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { if(t.getButton() == MouseButton.SECONDARY) { cm.show(table, t.getScreenX(), t.getScreenY()); } } }); 
+10
source share

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(rowMenu) .otherwise((ContextMenu)null)); return row; } }); 
+14
source share

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

+10
source share

All Articles