Context Menu on a row of TableView?
try this..
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());
}
}
});
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
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;
}
});