【问题标题】:How to avoid closing popup menu on mouse clicking in javafx combobox?如何避免在 javafx 组合框中单击鼠标时关闭弹出菜单?
【发布时间】:2015-08-11 07:16:22
【问题描述】:

我有自定义 ListCell 的组合框:

private class SeverityCell extends ListCell<CustomItem> {
    private final CustomBox custombox;

    {
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 
        custombox = new CustomBox();
    }

    @Override 
    protected void updateItem(CustomItem item, boolean empty) {         
        super.updateItem(item, empty);
        if (null != item) {
            //...
        }
        setGraphic(custombox);
    }
}

combobox.setCellFactory(new Callback<ListView<CustomItem>, ListCell<CustomItem>>() {
    @Override public ListCell<CustomItem> call(ListView<CustomItem> p) {
        return new SeverityCell();
    }
});

当我点击 mu 自定义组件弹出关闭,但我想避免它。我需要重写哪个方法/事件?

【问题讨论】:

    标签: combobox javafx


    【解决方案1】:

    ComboBox 在内部使用ListView 来渲染其项目。它的皮肤等级也是ComboBoxListViewSkin。在这个类的源代码中有一个布尔标志来控制弹出隐藏行为:

    // Added to allow subclasses to prevent the popup from hiding when the
    // ListView is clicked on (e.g when the list cells have checkboxes).
    protected boolean isHideOnClickEnabled() {
        return true;
    }
    

    在listview上使用:

           _listView.addEventFilter(MouseEvent.MOUSE_RELEASED, t -> {
                // RT-18672: Without checking if the user is clicking in the
                // scrollbar area of the ListView, the comboBox will hide. Therefore,
                // we add the check below to prevent this from happening.
                EventTarget target = t.getTarget();
                if (target instanceof Parent) {
                    List<String> s = ((Parent) target).getStyleClass();
                    if (s.contains("thumb")
                            || s.contains("track")
                            || s.contains("decrement-arrow")
                            || s.contains("increment-arrow")) {
                        return;
                    }
                }
    
                if (isHideOnClickEnabled()) {
                    comboBox.hide();
                }
            });
    

    因此,您可以(并且可能应该)使用自定义皮肤来实现您想要的行为。但是,解决方法可以是

    combobox.setSkin( new ComboBoxListViewSkin<CustomItem>( combobox )
    {
        @Override
        protected boolean isHideOnClickEnabled()
        {
            return false;
        }
    } );
    

    并手动隐藏弹出窗口,例如更改值时:

    combobox.valueProperty().addListener( new ChangeListener()
    {
        @Override
        public void changed( ObservableValue observable, Object oldValue, Object newValue )
        {
            combobox.hide();
        }
    });
    

    请注意,我没有完全测试这种匿名的内皮方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多