如何避免在javafx组合框中单击鼠标时关闭弹出菜单? [英] How to avoid closing popup menu on mouse clicking in javafx combobox?
问题描述
我有一个带有自定义ListCell的组合框:
I have combobox with custom 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时,自定义组件弹出窗口关闭,但我想避免这种情况。我需要覆盖哪个方法/事件?
When I click on mu custom component popup closes, but I want to avoid it. Which method/event I need to override?
推荐答案
ComboBox
内部使用 ListView
用于呈现其项目。同样,它的皮肤类是 ComboBoxListViewSkin
。在此类的源代码中,有一个布尔标志来控制弹出窗口的隐藏行为:
ComboBox
internally utilizes ListView
for rendering its items. Also its skin class is ComboBoxListViewSkin
. In a source code of this class there is boolean flag to control popup hiding behavior:
// 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.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();
}
});
因此,您可以(并且可能应该)使用自定义外观来实现所需的行为。但是,解决方法可以是
So the behavior you want can be (and probably should be) implemented with custom skin. However, the workaround can be
combobox.setSkin( new ComboBoxListViewSkin<CustomItem>( combobox )
{
@Override
protected boolean isHideOnClickEnabled()
{
return false;
}
} );
,并在例如更改值时手动隐藏弹出窗口:
and manually hide the popup, when the value is changed for instance:
combobox.valueProperty().addListener( new ChangeListener()
{
@Override
public void changed( ObservableValue observable, Object oldValue, Object newValue )
{
combobox.hide();
}
});
请注意,我没有完全测试这种匿名的内部皮肤方法。
Note please, I didn't fully test this anonymous inner skin approach.
这篇关于如何避免在javafx组合框中单击鼠标时关闭弹出菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!