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() + ")";
        names.add(tmp);
    }

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


    ArrayList<String> addNames = new ArrayList<>(names);
    addNames.add(0, "");
    ObservableList<String> add = FXCollections.observableList(addNames);
    addNameChoiceBox.setItems(add);
    addNameChoiceBox.setValue(add.get(0));
}

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

    try {
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()) {
            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;
}

@FXML
public void addNewWorkerButton(ActionEvent event) {
    String name = workerNameTextField.getText();
    workerNameTextField.setText("");
    db.addWorker(name);
    addWorkerAnchorPane.setVisible(false);
    mainAnchorPane.setOpacity(1);
    mainAnchorPane.setDisable(false);

    setNamesChoiceBoxes();
}

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: https://imgur.com/a/N4JarK7

It should be like this... (since I set the value to "All" in method...): https://imgur.com/a/ZAEB7A3

Related Questions