Linked Questions

Popular Questions

How to refresh a ChoiceBox in JavaFX?

Asked by At

I would like to refresh the choice box after I added a new value it should be shown there.

I read all the topics about this that I found on stackoverflow but none of these worked.

public void setNamesChoiceBoxes() {
    ArrayList<Worker> workers = new ArrayList<>();
    ArrayList<String> names = new ArrayList<>();

    workers = db.getWorkers();

    for (Worker i : workers) {
        String tmp = i.getName() + " (" + i.getID() + ")";

    ArrayList<String> searchNames = new ArrayList<>(names);
    searchNames.add(0, "All");
    ObservableList<String> search = FXCollections.observableList(searchNames);

    ArrayList<String> addNames = new ArrayList<>(names);
    addNames.add(0, "");
    ObservableList<String> add = FXCollections.observableList(addNames);

public ArrayList<Worker> getWorkers() {
    ArrayList<Worker> workers = new ArrayList<>();
    String sql = "select * from names";

    try {
        ResultSet rs = statement.executeQuery(sql);
        while ( {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            workers.add(new Worker(id, name));
    } catch (Exception ex) {
        System.out.println("Exception in class \"DB\" (\" public ArrayList<Worker> getWorkers()\" failed): " + ex);
    return workers;

public void addNewWorkerButton(ActionEvent event) {
    String name = workerNameTextField.getText();


I get the worker names from the database when I start the program, it works perfectly. When I add a new name to the DB, and call the "setNamesChoiceBoxes" method (to refresh the choicebox from DB), it gives alot of errors, although the new name is in the Choice Box list, but the "searchNameChoiceBox" value should be "All" but it is "".

After I added a new name choice box looks like this:

It should be like this... (since I set the value to "All" in method...):

Related Questions