Context Menu visibility in TableView JavaFX


I am creating TableView in JavaFX. In which I want to show Context Menu in right click of mouse in tableView. So I am adding an EventHandler on table as given below :

    TableView tableView=new TableView();

    EventHandler event = new EventHandler<MouseEvent>() {
        public void handle(MouseEvent me) {
            if (me.getButton() == MouseButton.SECONDARY) {
                tableView.getContextMenu().show(tableView, me.getSceneX(), me.getSceneY());
    tableView.addEventHandler(MouseEvent.MOUSE_CLICKED, event);

But my problem is that Context Menu is visible wherever I right click on any part of table.

I want to do that Context Menu should be only visible if I clicked on any rows in TableView.

i.e. How would I get row number in TableView at specific point, So that my Context Menu should be only visible, if I clicked on any row of TableView.

12/21/2012 4:53:57 AM

The best solution I found was to check if the y coordinate is outside of the bounds of the column header and then to explicitly show the menu.

ContextMenu visibleMenu = null;
tableView.setOnMouseClicked((MouseEvent e) -> {
    if (visibleMenu !=null) {
        visibleMenu = null;
    if (e.getButton()==MouseButton.SECONDARY) {
        double columnHeaderHeight = tableView.lookup(".column-header-background").getBoundsInLocal().getHeight();
        if (e.getY()>columnHeaderHeight) {
            visibleMenu = getContextMenu(); // build on the fly or use a prebuild menu
  , e.getScreenX(), e.getScreenY());
        } else {
            // you could show a header specific context menu here

The added benefit is that you can build the context menu on the fly with context sensitive items (that for example only appear if a certain type of cell is selected), or just reuse a prebuild contextmenu as setContextMenu does, up to you.

9/14/2016 11:29:41 PM

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