Combobox + Arraylist + SQL

Asked

Viewed 584 times

0

Hello, I have the following problem in question:

I made an array list to list data in a combo box, but it only lists the data from the first table, in this case: "catdesc", which is the description of a car category, whether it is Sporty, etc. But in the same table, has a column called catvalordiaria, IE, is the daily value of this car category.

In the combobox appears only the description:

inserir a descrição da imagem aqui

I want to show, next to this description, the daily amount, ex: Sports - R $ 39,90; I don’t know if the problem is because the figure is double, or sla, I need your help. Here is my code from "Categoriadao" and just below Servicos.java, where you list the categories in the Combo Box.

package model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import model.bean.Categoria;
import model.connection.ConnectionFactory;


public class CategoriaDao {

    Connection con=null;
    String sql;
    ResultSet rs;
    PreparedStatement pstm;

    ArrayList<Categoria> listacat=new ArrayList<>();

    public List<Categoria> listarCategorias(){

        try{           

         con=ConnectionFactory.getConnection();         
         sql= "SELECT catcodigo,catdesc,catvalordiaria FROM categoria ORDER BY catdesc";    
         pstm=con.prepareStatement(sql);            
         rs=pstm.executeQuery(sql);

         while(rs.next()){

         Categoria cat = new Categoria();

         cat.setCatCodigo(rs.getInt(1));
         cat.setCatDescricao(rs.getString(2));
         cat.setCatValorDiaria(rs.getDouble(3));
         listacat.add(cat);

         }

        }catch(Exception erro){

            JOptionPane.showMessageDialog(null,"Erro PSTM "+erro.getMessage());


        }

        return listacat;

            }

}
    public void preencherComboCategoria(JComboBox comboCategoria){

        CategoriaDao cat = new CategoriaDao();

        List<Categoria> listagem2 = cat.listarCategorias();

        for(Categoria c:listagem2){


            comboCategoria.addItem(c);


    }

}

}

1 answer

0


It is possible to abstract the data needed for a new transition object, so you would not use the entity Categoria direct on a visualization layer, which is considered a bad practice. That way you could have an attribute that is the concatenation of catdesc with catvalordiaria.

For example:

public class CategoriaViewModel {
    private int codigo;
    private String descricao;

    public String getCodigo() { return this.codigo; }
    public void setCodigo(String codigo) { this.codigo = codigo; }
    public String getDescricao() { return this.descricao; }
    public void setDescricao(String desc) { this.descricao = desc; } 
}

This would be your transition object, which you will display in the view. To get it we need to fill it out according to the data coming from the DAO layer. For this we can use a converter, where you will pass objects of type Categoria and it will convert to objects like CategoriaViewModel.

public class CategoriaConversor() {

    /**
     * Em geral, os métodos de conversão não recebem tipos List,
     * e sim o tipo em si, no caso Categoria. 
     * Porém pra simplificar o exemplo será com list.
     **/
    public List<CategoriaViewModel> convert(List<Categoria> categorias) {
        List<CategoriaViewModel> viewModels = new ArrayList<CategoriaViewModel>();

        for (Categoria cat : categorias) { 
            CategoriaViewModel viewModel = new CategoriaViewModel();
            viewModel.setCodigo(cat.getCatCodigo());

            //Aqui é onde a descrição é concatenada e montada com desc + valordiaria
            viewModel.setDescricao(String.format("%s - %s", cat.getCatCodigo(),
                                   cat.getCatValorDiaria()));
            viewModels.add(viewModel);
        }

        return viewModels;
    }
}

And in your Combobox filling method you convert to the type CategoriaViewModel:

CategoriaConverter converter = new CategoriaConverter();
List<CategoriaViewModel> categorias = converter.convert(cat.listarCategorias());

for(CategoriaViewModel cat : categorias) {
    comboCategoria.add(cat);
}

This way you avoid using the direct entity object in the preview layer, keeping it unchanged and true to what you brought from the database if you use the same instance for other purposes.

Browser other questions tagged

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