Combobox refresh value and listview when object content change

大憨熊 提交于 2019-12-02 07:50:40

Everytime a new value is added to the object list, set the combobox value again. Works for me. I did a small example to show this. Hope it is helpful

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class ComboTest extends Application {
    int i =0;
    ObservableList<String> list = FXCollections.observableArrayList("A","B");
    ComboBox<String> combo = new ComboBox();
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        combo.setPromptText("Testing combobox");
        combo.setPrefWidth(300);
        btn.setText("Add items to list");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                list.add(String.valueOf(i));
                System.out.println("size of list " + list.size() );
                i++;
               combo.setItems(list);
            }
        });
        combo.setItems(list);
        VBox root = new VBox();
        root.getChildren().addAll(btn,combo);
        root.setSpacing(20);
        root.setAlignment(Pos.CENTER);
        Scene scene = new Scene(root);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!