javafx组合框上下文菜单未显示

时间:2014-11-06 10:50:59

标签: combobox javafx contextmenu

我的问题是: 我做了一个组合框,我想在它的元素上使用上下文菜单,所以当我设置如下所示的cellfactory时,我再也看不到这些项目了,上下文菜单也没有显示。

CBXGroups.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
    public ListCell<String> call(ListView<String> param) {
    final ListCell<String> cell = new ListCell<String>();
    final ContextMenu cellMenu = new ContextMenu();
    MenuItem rimuoviDalControllo = new MenuItem("RIMUOVI DAL CONTROLLO");
    MenuItem rimuoviDefinitivamente = new MenuItem("RIMUOVI DEFINITIVAMENTE");
    rimuoviDalControllo.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {
        Service.deleteGroupFromControl(cell.getText(),CBXControllo.getSelectionModel().getSelectedItem());
        populateLists();
        }
    });
    rimuoviDefinitivamente.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {
        Service.deleteGroup(cell.getText());
        populateLists();
        }
    });
    cellMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent event) {
        cell.requestFocus();
        }
    });
    cellMenu.getItems().addAll(rimuoviDalControllo,rimuoviDefinitivamente);
    cell.contextMenuProperty().bind(Bindings.when(Bindings.isNotNull(cell.itemProperty())).then(cellMenu).otherwise((ContextMenu) null));
    return cell;
    }
});

1 个答案:

答案 0 :(得分:0)

您无法看到这些项目,因为您尚未在ListCell中设置文字。您可以使用单行代码执行此操作:

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

上下文菜单比较复杂,我真的没有解决方案。问题是ComboBox使用PopupControl来显示列表视图,弹出控件的autoHide设置为true。因此,当您单击列表视图时,弹出窗口将关闭(阻止您查看上下文菜单)。没有办法访问弹出控件,所以我认为没有任何办法可以做到这一点。

使用组合框中的项目注册上下文菜单似乎是一件不寻常的事情;我想知道是否有更好的方法来做你想做的事。 MenuButton在某些方面类似于ComboBox(控件显示带有选项的弹出窗口),但它有一个菜单层次结构,因此您可以包含级联菜单。这可能会提供您想要的功能。

相关问题