为同一项目触发组合框选择事件
问题描述:
我有一个ComboBox
,它具有以下代码所示的实现。我面临的问题是我只能触发ChangeListener
一次选择的项目。我想触发多次,因为我点击相同的项目。为同一项目触发组合框选择事件
int lastGridRowPos = 4;
ObservableList<String> options = FXCollections.observableArrayList(
"IdentityFile",
"LocalForward",
"RemoteForward",
"ForwardAgent",
"ForwardX11"
);
ComboBox propertyBox = new ComboBox(options);
propertyBox.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue ov, String t, String t1) {
System.out.println("SELECTED=" + t1);
int rowCounter = getRowCount(grid);
grid.add(new Label(t1), 0, rowCounter + 1);
TextField field = newTextFieldWithIdPrompt(t1.toUpperCase(), "");
grid.add(field, 1, rowCounter + 1);
propertyBox.getSelectionModel().clearSelection();
}
});
我试图用propertyBox.getSelectionModel().clearSelection();
但它不工作以清除选择,这样我可以在同一项目再次点击(希望组合框看到了项目的变化)。
答
我几乎可以肯定,一个简单的解决方案存在,但你可以尝试使用setCellFactory
并添加EventFilter
返回的ListCell
实例:
propertyBox.setCellFactory(param -> {
final ListCell<String> cell = new ListCell<String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty)
setText(item);
}
};
cell.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
propertyBox.setValue(null);
propertyBox.getSelectionModel().select(cell.getItem());
e.consume();
});
return cell;
});
这些ListCell
旨意捕捉鼠标按下事件列表ComboBox
中的项目并消耗这些事件。然后他们手动将ComboBox
的valueProperty
设置为空(以删除选择),然后将该属性设置为ListCell
显示的项目。
然后在的ChangeListener
的valueProperty
你只需要检查null
S:
propertyBox.valueProperty().addListener((obs, oldVal, newVal) -> {
if (newVal != null)
System.out.println("Selected: " + newVal);
});
附加说明:
我不知道你的确切使用情况,但也许一个Menu
与MenuItem
s是更好的解决方案。
感谢您的解决方案(我仍然必须尝试在我的情况)。现在,当你说出这些话时,我想知道为什么菜单不适合我。我会看看菜单。我想要做的就是提供一个供用户选择的物品清单,他可以从哪里允许他们一次又一次地选择相同的物品。 – summerNight