JavaFX: ComboBox<Test> get and set item according to ID field of Test

1k Views Asked by At

I have a ComboBox. And this combobox has items=ObservableList<Test>. In order to work with object Test I set cell factory for combobox:combobox.setCellFactory(...). Class Test is the following:

public class Test{
  private Integer id;
  private String name;
  //+getters and setters
}

Questions:

  1. How can I make combobox set selected Test with id=X (list of Tests is already added to combobox)?
  2. How can I get currently selected Test?
2

There are 2 best solutions below

9
On BEST ANSWER

With ComboBox<Test> combo :

1) combo.getSelectionModel().select( X ); where X is an index of Test
2) combo.getSelectionModel().getSelectedItem(); returns the Test

1
On

Heres the code that selects one Test instance by id.

public void selectTestById(Integer id){
  for(Test test : comboBox.getItems()){
    if(test.getId().equals(id)){
      comboBox.getSelectionModel().select(test);
      return;
    }
  }
}