如何围绕整个对象设置上下文菜单

How do I set a context menu around a whole object

看你看图,我只有在橙色区域点击右键,才能弹出上下文菜单。当我在整个对象周围单击时(如在进度条等中),我希望能够右键单击并获得上下文菜单。所有橙色的项目都使用列表视图显示,我使用 Hbox 来组织它们,因此复选框和进度条可以在某行上。我试过这个答案 but it didn't really help.

这是我的代码

// Declare list that will hold the item
    ObservableList<HBox> itemList = FXCollections.observableArrayList();
    // Declare List View that will contain all the items
    ListView itemlistView = new ListView<>();
    // Get the items within the week
    VBitem.displayByWeek();
    // Add the items to the item list
    for (int i = 0; i < VBitem.weekList.size(); i++) {
        itemList.add(VBitem.weekList.get(i).display());
    }
    // Add the items to the list view
    itemlistView.setitems(itemList);
    // Style the list
    itemlistView.getStylesheets().add(getClass().getResource("Main.css").toExternalForm());
    // Add the list view to the scroll pane
    fx_content_scroll.setContent(itemlistView);

    itemlistView.setCellFactory(ly -> {
        ListCell<HBox> cell = new ListCell<>();
        ContextMenu contextMenu = new ContextMenu();
        // Menu items
        Menuitem editMenu = new Menuitem("Edit");
        Menuitem deleteMenu = new Menuitem("Delete");



        //System.out.println("Cell " + cell.getitem().item.info());
        editMenu.textProperty().bind(Bindings.format("Edit \"%s\"",cell.itemProperty()));
        //edititem.textProperty().bind(Bindings.format("Edit \"%s\"", cell.itemProperty()));
        //editMenu.textProperty().bind(cell.itemProperty().asString());
        editMenu.setOnAction(event -> {
            System.out.println("HI "+cell.itemProperty());
            //System.out.println("Just edited "+cell.getitem().item.info());
            System.out.println("Editing");
        });
        // Add menu items to ContextMenu
        contextMenu.getitems().addAll(editMenu, deleteMenu);



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

        return cell;

    });

据我了解,您想在包含复选框和进度条的窗格中的任何位置显示上下文菜单。将 ContextMenu 添加到 Control 很简单;您使用 Control.setContextMenu(...); 方法,但是,HBox 是一个窗格,而不是控件。

要将上下文菜单添加到 HBox,您可以使用 Node.setOnContextMenuRequested(...) 方法在请求上下文菜单时接收事件。在此期间,您可以在活动地点显示上下文菜单,达到预期的效果。

    HBox box = new HBox();
    box.getChildren().addAll(...);        

    MenuItem editMenu = new MenuItem("Edit");
    editMenu.setOnAction(e -> {
        // Do something
    });

    MenuItem deleteMenu = new MenuItem("Delete");
    deleteMenu.setOnAction(e -> {
        // Do something
    });

    ContextMenu menu = new ContextMenu(editMenu, deleteMenu);
    box.setOnContextMenuRequested(e -> {
        menu.show(box.getScene().getWindow(), e.getScreenX(), e.getScreenY());
    });

这将在您用来组织 CheckBox 和 ProgressBar 的 HBox 中的任何位置打开一个 ContextMenu。这可以很容易地调整以适合您想要的区域。