我有ObservableList<Fruits> fruits
。每个水果对象都有名称和值参数。对象是:{“ apples”,22},{“ oranges”,3}和{“ pears”,5}。我将这些项目添加到ComboBox
:
fruitComboBox.setItems(fruits);
如何ComboBox
根据对象名称从中获取项目索引?例如获取“橙色”对象的索引?
我需要获取项目的索引,以便可以使用:
fruitComboBox.getSelectionModel.select(index);
完整的代码如下所示:
fruitComboBox.setItems(fruits);
fruitFactory = lv -> new ListCell<Fruits>){
@Override
protected void updateItem(Fruits fruit, boolean empty) {
super.updateItem(fruit, empty);
setText(empty ? "" : fruit.getName + ": " + fruit.getValue);
}
};
fruitComboBox.setCellFactory(fruitFactory);
fruitComboBox.setButtonCell(fruitFactory.call(null));
对于不同的人,我需要默认选择不同的水果。我尝试使用:
fruitComboBox.getSelectionModel().select(orangeObject);
但是它没有显示格式化的对象ButtonCell
,也没有打开任何选择ComboBox
。使用索引给出了完美的结果:
fruitComboBox.getSelectionModel().select(2);
唯一的问题是,我不知道如何ComboBox
基于其参数之一获取item中的索引。
为什么不做:
for (Fruit fruit : fruitComboBox.getItems()) {
if ("oranges".equals(fruit.getName())) {
fruitComboBox.getSelectionModel().select(fruit);
break ;
}
}
或者,如果您更喜欢基于流的解决方案
fruitComboBox.getItems().stream()
.filter(fruit -> "oranges".equals(fruit.getName()))
.findAny()
.ifPresent(fruitComboBox.getSelectionModel()::select);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句