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, Side.BOTTOM, 0, 0);
5/11/2017 11:11:03 AM

Accepted Answer

try this..

ContextMenu cm = new ContextMenu();
MenuItem mi1 = new MenuItem("Menu 1");
MenuItem mi2 = new MenuItem("Menu 2");

table.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

    public void handle(MouseEvent t) {
        if(t.getButton() == MouseButton.SECONDARY) {
  , t.getScreenX(), t.getScreenY());
1/6/2018 12:44:26 PM

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

    new Callback<TableView<Person>, TableRow<Person>>() {
        public TableRow<Person> call(TableView<Person> tableView) {
            final TableRow<Person> row = new TableRow<>();
            final ContextMenu rowMenu = new ContextMenu();
            MenuItem editItem = new MenuItem("Edit");
            MenuItem removeItem = new MenuItem("Delete");
            removeItem.setOnAction(new EventHandler<ActionEvent>() {

                public void handle(ActionEvent event) {
            rowMenu.getItems().addAll(editItem, removeItem);

            // only display context menu for non-empty rows:
            return row;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow