Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx ListView ContextMenu

I've had a look at some previous questions on this but they only seem to work whereby a click anywhere in the listview will trigger the event, I am looking for a solution where the event would only be triggered and open a context menu when a property in the listview is clicked.

like image 828
user3537381 Avatar asked Dec 03 '22 17:12

user3537381


1 Answers

This is actually a duplicate, but I can't find the previous question.

You should use a cell factory and set the context menu on the cells. You can then make sure you only set the context menu on non-empty cells. (This also gives you the opportunity to have item-specific context menus.)

Here's a simple example:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ListViewContextMenuExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        ListView<String> listView = new ListView<>();
        listView.getItems().addAll("One", "Two", "Three");

        listView.setCellFactory(lv -> {

            ListCell<String> cell = new ListCell<>();

            ContextMenu contextMenu = new ContextMenu();


            MenuItem editItem = new MenuItem();
            editItem.textProperty().bind(Bindings.format("Edit \"%s\"", cell.itemProperty()));
            editItem.setOnAction(event -> {
                String item = cell.getItem();
                // code to edit item...
            });
            MenuItem deleteItem = new MenuItem();
            deleteItem.textProperty().bind(Bindings.format("Delete \"%s\"", cell.itemProperty()));
            deleteItem.setOnAction(event -> listView.getItems().remove(cell.getItem()));
            contextMenu.getItems().addAll(editItem, deleteItem);

            cell.textProperty().bind(cell.itemProperty());

            cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
                if (isNowEmpty) {
                    cell.setContextMenu(null);
                } else {
                    cell.setContextMenu(contextMenu);
                }
            });
            return cell ;
        });

        BorderPane root = new BorderPane(listView);
        primaryStage.setScene(new Scene(root, 250, 400));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
like image 61
James_D Avatar answered Dec 22 '22 11:12

James_D