Search code examples
javafxcombobox

How to get item index from ComboBox?


I have ObservableList<Fruits> fruits. Each fruit object has name and value parameters. Objects are: {"apples", 22}, {"oranges", 3} and {"pears", 5}. I added those items to ComboBox:

fruitComboBox.setItems(fruits);

How can I get item index from this ComboBox based on object's name? For example get index of "oranges" object?

I need to get index of item, so that I can use:

fruitComboBox.getSelectionModel.select(index);

full code will look like:

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));

For different people I need to select by default different fruits. I tried using:

fruitComboBox.getSelectionModel().select(orangeObject);

But it showed not formatted object in ButtonCell, also it didn't have any selection in open ComboBox. Using index gave perfect results:

fruitComboBox.getSelectionModel().select(2);

The only problem is, I don't know how I can get index of item in the ComboBox based on one of its parameters.


Solution

  • Why not just do:

    for (Fruit fruit : fruitComboBox.getItems()) {
        if ("oranges".equals(fruit.getName())) {
            fruitComboBox.getSelectionModel().select(fruit);
            break ;
        }
    }
    

    or, if you prefer a stream-based solution

    fruitComboBox.getItems().stream()
        .filter(fruit -> "oranges".equals(fruit.getName()))
        .findAny()
        .ifPresent(fruitComboBox.getSelectionModel()::select);