JavaFX: ComboBox<Test> 根据Test的ID字段获取和设置item

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

我有一个组合框。这个组合框有 items=ObservableList<Test>。为了使用对象测试,我为组合框设置了单元格工厂:combobox.setCellFactory(...)。 Class 测试如下:

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

问题:

  1. 如何使组合框设置为 id=X 的选定测试(测试列表已添加到组合框)?
  2. 如何获取当前选择的测试?

ComboBox<Test> combo :

1) combo.getSelectionModel().select( X ); 其中 X 是 Test
的索引 2) combo.getSelectionModel().getSelectedItem(); returns Test

这是通过 id 选择一个 Test 实例的代码。

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