Problem returning values to a combobox from a query

Asked

Viewed 142 times

0

my DAO

public List<Departamento> read(){
    List<Departamento> departamentos = new ArrayList();
    String query = "SELECT * FROM departamentos";
    try {
    PreparedStatement ps = con.prepareStatement(query);
    ResultSet rs = ps.executeQuery();
    while(rs.next()){
       Departamento departamento = new Departamento();
       departamento.setId_departamento(rs.getInt("id_departamentos"));
       departamento.setNome_setor(rs.getString("nome_setor"));
       departamentos.add(departamento);
    }
    ps.close();
    rs.close();
    }catch (SQLException ex) {
        Logger.getLogger(DepartamentoDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return departamentos;
}

my controller:

@FXML
private JFXComboBox<Departamento> cbDepart;
private ObservableList<Departamento> obsDepartamentos;
public void initialize(URL url, ResourceBundle rb) {
    DepartamentoDAO dao = new DepartamentoDAO();
    for(Departamento d: dao.read()){
       obsDepartamentos = FXCollections.observableArrayList(d);
       cbDepart.setItems(obsDepartamentos);
    }
}

my model I created to string:

@Override
public String toString() {
    return getNome_setor();
}

good when debugging I saw that really after query the list matches with the Qtd in the database but in the combo box only one record of the table appears and my list takes 4 records

and I realized that the problem is in my controller, but I don’t know how to solve.

1 answer

1


The problem is inside your foreach

 for(Departamento d: dao.read()){
       **obsDepartamentos = FXCollections.observableArrayList(d);**
       cbDepart.setItems(obsDepartamentos);
    }

At every iteration of foreach is overwriting the observableArrayList with one element only,the correct would be to pass a list as parameter to the FXCollections.observableArrayList(). Like your dao.read() returns a list, removes your foreach and simply does this:

obsDepartamentos = FXCollections.observableArrayList(dao.read());
cbDepart.setItems(obsDepartamentos);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.