ComboBox

基础使用
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll("item1", "item2", "item3", "item4", "item5");
comboBox.setPlaceholder(new Label("Placeholder"));
comboBox.setEditable(true);
comboBox.setPromptText("PromptText");
comboBox.setVisibleRowCount(3);
comboBox.editorProperty().addListener(new ChangeListener<TextField>() {
@Override
public void changed(ObservableValue<? extends TextField> observable, TextField oldValue, TextField newValue) {
}
});
comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
}
});
自定义对象
Student student1 = new Student("Student1", 10, 1);
Student student2 = new Student("Student2", 11, 2);
Student student3 = new Student("Student3", 12, 3);
ComboBox<Student> comboBox = new ComboBox<>();
comboBox.getItems().addAll(student1, student2, student3);
comboBox.setPlaceholder(new Label("Placeholder"));
comboBox.setValue(student2);
comboBox.setEditable(true);
comboBox.setConverter(new StringConverter<Student>() {
@Override
public String toString(Student object) {
if (object == null) {
return "";
}
return object.name + "-" + object.id;
}
@Override
public Student fromString(String string) {
System.out.println("string = " + string);
comboBox.getItems().add(new Student(string, 1, 99));
return null;
}
});
comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Student>() {
@Override
public void changed(ObservableValue<? extends Student> observable, Student oldValue, Student newValue) {
}
});
自定义 Item

comboBox.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> param) {
return new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
this.setStyle("-fx-text-fill: #0aa");
this.setText(item);
this.setGraphic(new ImageView("image\\stash.png"));
}
}
};
}
});

comboBox.setCellFactory(new Callback<ListView<Student>, ListCell<Student>>() {
@Override
public ListCell<Student> call(ListView<Student> param) {
return new ListCell<Student>() {
@Override
protected void updateItem(Student item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
this.setText(comboBox.getConverter().toString(item));
this.setFont(Font.font(20));
this.setTextFill(Paint.valueOf("#088"));
}else {
setText(null);
setGraphic(null);
}
}
};
}
});
修改 Item 值刷新列表
ObservableList<Student> items = comboBox.getItems();
items.get(index).name = "修改后";
SingleSelectionModel<Student> selectionModel = comboBox.getSelectionModel();
selectionModel.clearSelection();
selectionModel.select(index);