当底层对象发生更改时,JavaFx ComboBox不会更新其选定的项目。举一个简单的例子:
StringProperty item1 = new SimpleStringProperty("Item-1");
StringProperty item2 = new SimpleStringProperty("Item-2");
StringProperty item3 = new SimpleStringProperty("Item-3");
ObservableList<StringProperty> items = FXCollections.observableArrayList(item1, item2, item3);
ComboBox comboBox = new ComboBox();
comboBox.setItems(items);
comboBox.getSelectionModel().select(item1);
StackPane root = new StackPane();
root.getChildren().add(comboBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
Timeline timeline1 = new Timeline(new KeyFrame(
Duration.millis(1000), ae -> {
item1.set("Changing the string");
}));
timeline1.play();
希望ComboBox反映我对item1
所做的更改。有没有办法做到这一点?
答案 0 :(得分:2)
假设您已经在组合框中定义了单元工厂和按钮单元格,以便您可以很好地显示列表中的元素,如果您实现了将单元格的text属性绑定到相应的属性,它将起作用:< / p>
public static class StringPropertyCell extends ListCell<StringProperty> {
@Override
protected void updateItem(StringProperty item, boolean empty) {
super.updateItem(item, empty);
textProperty().unbind();
if (item != null && ! empty) {
textProperty().bind(item);
}
}
}
然后,显然,
ComboBox<StringProperty> comboBox = new ComboBox<>();
comboBox.setItems(items);
comboBox.getSelectionModel().select(item1);
comboBox.setCellFactory(lv -> new StringPropertyCell());
comboBox.setButtonCell(new StringPropertyCell());
否则,您需要使用extractor构建基础列表:
ObservableList<StringProperty> items =
FXCollections.observableArrayList(e -> new Observable[] {e});
items.addAll(item1, item2, item3);
另请注意,您只需使用普通String
列表而不是StringProperty
列表来实际达到预期效果(至少在您发布的示例代码中):
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ComboBoxTest extends Application {
@Override
public void start(Stage primaryStage) {
ObservableList<String> items = FXCollections.observableArrayList("Item-1", "Item-2", "Item-3");
ComboBox<String> comboBox = new ComboBox<>();
comboBox.setItems(items);
comboBox.getSelectionModel().select(0);
StackPane root = new StackPane();
root.getChildren().add(comboBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
Timeline timeline1 = new Timeline(new KeyFrame(
Duration.millis(1000), ae -> {
items.set(0, "Changing the string");
}));
timeline1.play();
primaryStage.setScene(new Scene(new StackPane(comboBox), 300, 100));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}