如何更改 contextMenu 默认鼠标按钮?

How to change contextMenu default mouse button?

我有一个 contextMenu 并将其添加到一个按钮中。当我在按钮上左键单击(PRIMARY)时,我希望显示 contextMenu。我怎样才能做到这一点?因为默认情况下只需右键单击即可。

我试过这种方法,但没有用

Button sortBy = new Button();

ContextMenu sortByMenu = new ContextMenu();
    sortByMenu.addEventFilter(MouseEvent.MOUSE_PRESSED, ev -> {
        if (ev.getButton() == MouseButton.PRIMARY) {
            //does not do anything
        }
    });

 sortBy.setContextMenu(sortByMenu);

菜单按钮

MenuButton is a button which, when clicked or pressed, will show a ContextMenu.

来自 javadoc 的示例代码:

MenuButton m = new MenuButton(
    "Eats"
);
m.getItems().addAll(
    new MenuItem("Burger"),
    new MenuItem("Hot Dog")
);

选择框

你也可以考虑 ChoiceBox,这取决于你想做什么。

The ChoiceBox is used for presenting the user with a relatively small set of predefined choices from which they may choose.

ChoiceBox<String> cb = new ChoiceBox<>();
cb.getItems().addAll(
    "item1",
    "item2",
    "item3"
);

对于 select 选择列表中的 sortBy 排序字段,ChoiceBox 可能是一个不错的选择。