How to get a “delete row” menu item working on a JavaFX TableView row

As a quick note to self, this is what I had to do to get a “Delete” menu item working on a JavaFX TableView row:

/**
  * there may be other ways to do this, but to get a "Delete" menu item
  * working on a table row, this seems to be what you have to do, which is
  * to create a custom ContextMenu for each row.
  * @see https://gist.github.com/james-d/7758918
  */
tableView.setRowFactory(new Callback[TableView[Note], TableRow[Note]]() {

    @Override
    def call(tableView: TableView[Note]): TableRow[Note] = {

        // TODO i added the TableRow code shown so i can show a tooltip over the Note column
        // (actually shows over all columns)
        //val row: TableRow[Note] = new TableRow()
        val row = new TableRow[Note]() {
            override def updateItem(item: Note, empty: Boolean) {
                super.updateItem(item, empty)
                if (item != null) {
                    val tooltip = new Tooltip()
                    tooltip.setText(getItem().getNote)
                    setTooltip(tooltip)
                }
            }
        }

        val addNoteMenuItem = new MenuItem("Add Note")
        val deleteNoteMenuItem = new MenuItem("Delete Note")
        addNoteMenuItem.setOnAction(new AddNoteEventHandler(tableView, db))
        deleteNoteMenuItem.setOnAction(new DeleteNoteEventHandler(tableView, row, db))

        val fullContextMenu = new ContextMenu()
        fullContextMenu.getItems().add(addNoteMenuItem)
        fullContextMenu.getItems().add(deleteNoteMenuItem)

        // for empty rows, only allow 'Add'
        //val addOnlyContextMenu = new ContextMenu()
        //addOnlyContextMenu.getItems().add(addNoteMenuItem)

        //TODO implement this properly
        //TODO don't allow Delete action on empty rows
        // `row.emptyProperty()` did not work as expected
        row.contextMenuProperty().bind(
            Bindings.when(row.visibleProperty())
                .then(fullContextMenu)
                .otherwise(fullContextMenu)
        )
        return row
    }
});

I started with this approach in my Notes application, but then decided to take another route, i.e., not using a popup menu on the TableView.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.