Problem with JTable

0

I have a problem with a JTable. I made a method in DAO that calculates a total of products consumed, this method is called on Screen in the register button, every time I register a precise consumption that calculates the quantity according to the value of the product and shows a total value. In fact it is calculating however only in the first register, if I register other consumptions, what shows me on the screen is only the first consumption, if I delete others and leave only the consumption of the first row of the table is only this that will be visualized. Below the method code.

DAO Method:

public Object mostra(String buscar) {

    Consumo consumoVO = new Consumo();
    ConsumoDAO consumoDAO = new ConsumoDAO();
    ModeloTabelaConsumo modelo = new ModeloTabelaConsumo();
    totalConsumo = 0.0;

    String sql = ("SELECT c.codConsumo, c.codHospedagem, c.codProduto, p.nomeProduto, " +
                  " c.quantidade, c.valorConsumo, c.status " +
                  " from consumo c " +
                  " INNER JOIN produto  p ON c.codProduto = p.codProduto " +
                   "INNER JOIN hospedagem AS H ON H.codHospedagem = C.codHospedagem " 
                 + " WHERE c.codHospedagem = " + buscar + " order by c.codConsumo ");

    getBanco().abrir();
    try {
        Statement stm = getBanco().getConexao().createStatement();
        //Faz a leitura no banco
        ResultSet rs = stm.executeQuery(sql);

        if (rs.next() == true) { //Achou
            consumoVO = new Consumo();
            consumoVO.setCodConsumo(rs.getInt("codConsumo"));
            consumoVO.setCodHospedagem(rs.getInt("codHospedagem"));
            consumoVO.setCodProduto(rs.getInt("codProduto"));
            consumoVO.setCodProduto(rs.getInt("nomeProduto"));                               
            consumoVO.setQuantidade(rs.getInt("quantidade"));
            consumoVO.setValorConsumo(rs.getDouble("valorConsumo"));
            consumoVO.setStatus(rs.getString("status"));

            totalConsumo = totalConsumo + (rs.getInt("quantidade") * rs.getDouble("valorConsumo"));

           } 

    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return consumoVO;
}

Consumption Screen Method:

void mostrar(String buscar){
   consumoDAO.mostra(buscar);     
    lblTotalConsumo.setText("Valor R$. " + consumoDAO.totalConsumo);

}   
    
asked by anonymous 21.05.2016 / 05:52

1 answer

1

What happened there is a logic error. The problem is in your if to verify that you found the item, but actually in place of if should be while . So it only returns the value of the first item. With while your totalConsumo will return correctly.

As is: if (rs.next()) { //Achou

How to stay: while (rs.next()) { //Achou

And as our colleague Diego F. reported, you do not have to compare with true, since the next() method already returns a boolean .

    
21.05.2016 / 21:09