Replacing an item in the ObservableList of a ComboBox always changes the current selected item if the replaced position is before the selected positlion.
import javafx.application.*;
import javafx.collections.*;
import javafx.event.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class ComboBoxModelTest2 extends Application {
int i;
ObservableList<String> model;
public void start(Stage stage) {
ComboBox<String> comboBox = new ComboBox<>();
model = FXCollections.observableArrayList("Start 0", "Start 1", "Start 2");
comboBox.itemsProperty().set(model);
comboBox.getSelectionModel().select(1);
Button button1 = new Button("Add");
button1.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent arg0) {
model.add("Item-" + (++i));
}
});
Button button2 = new Button("Change First");
button2.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent arg0) {
model.set(0, "Change");
}
});
VBox vbox = new VBox(7);
vbox.setAlignment(Pos.CENTER);
vbox.getChildren().addAll(comboBox, button1, button2);
Scene scene = new Scene(vbox, 400, 400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Appending Items with the first button works as expected.
Replacing the first item in the list with the second button will shift the selection
toward the end.
import javafx.application.*;
import javafx.collections.*;
import javafx.event.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class ComboBoxModelTest2 extends Application {
int i;
ObservableList<String> model;
public void start(Stage stage) {
ComboBox<String> comboBox = new ComboBox<>();
model = FXCollections.observableArrayList("Start 0", "Start 1", "Start 2");
comboBox.itemsProperty().set(model);
comboBox.getSelectionModel().select(1);
Button button1 = new Button("Add");
button1.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent arg0) {
model.add("Item-" + (++i));
}
});
Button button2 = new Button("Change First");
button2.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent arg0) {
model.set(0, "Change");
}
});
VBox vbox = new VBox(7);
vbox.setAlignment(Pos.CENTER);
vbox.getChildren().addAll(comboBox, button1, button2);
Scene scene = new Scene(vbox, 400, 400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Appending Items with the first button works as expected.
Replacing the first item in the list with the second button will shift the selection
toward the end.