Popular Jcombobox with Strings and Ids brought from the database

Asked

Viewed 2,116 times

0

I need a popular JComboBox with the data brought from a table in my Mysql Database, but I don’t know how to leave an item attached to the corresponding ID.

Example: ID 1 refers to the ADM profile and ID 2 refers to the Standard profile. If the user selects the ADM item, ID 1 must be inserted into the BD.

Is there any method or property that stores the ID without necessarily showing it on Jcombobox?

public void fillCB(){
    try{
        ResultSet rs;
        perfil.select();//esse método busca no BD os perfis existentes
        rs=perfil.getRs();//aqui eu pego o ResultSet existente na minha classe perfil
        while(rs.next()){
            cbPerfil.addItem(rs.getString("nome"));//e aqui populo a minha ComboBox com a descrição do perfil, porém preciso trazer o ID para relacionar com o item
        }
    }
    catch(SQLException erro){
        JOptionPane.showMessageDialog(null, "Erro!\n"+erro);
    }
}

Above the method code to fill the Combobox.

  • Is it a table with 2 fields? If so, I’ll give you a hint, create a comboboxmodel. Much easier, it makes your code organized and easy to maintain.

  • Yes, only 2 fields. Would have some example of use?

  • I’m on the phone now, but check out this example of this answer: https://answall.com/a/105753/28595

  • I read the example and saw that quote DAO, but my project does not have this implementation. I need to implement DAO or there is some other way?

  • To make it easier, add a [mcve] so you can execute your code. This makes it easier to think of a solution that suits you.

  • @diegofm edited the post with the code of my method

  • Did the answer help you? If yes, you can mark it as accepted by clicking on v the left of the answer :)

Show 2 more comments

1 answer

0


I think the most recommended option in this case is to use a customized version of a ComboBoxModel. Only for that, you also need to create a representation POJO of this table Perfil, something like this:

public class Perfil {

    private int id;
    private String nome;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    @Override
    public String toString() {
        return this.nome;
    }
}

The method toString() which I have overwritten (as it was done in this answer) is to display the profile name as a representation of the object in the combo.

As I said in the comments, the ideal is to separate responsibilities and create a class that interacts with the database separately, and not delegate this to the class that builds the screen, but as no more detail of the screen was presented, I will base myself on the question method. You must redeem the data from your table and assign the above class by creating a list of all the database items:

List<Perfil> lista = new ArrayList<>();

ResultSet rs;
perfil.select();//esse método busca no BD os perfis existentes
rs=perfil.getRs();//aqui eu pego o ResultSet existente na minha classe perfil
while(rs.next()){
    Perfil p  = new Perfil();
    p.setId(rs.getInt("id"));
    p.setNome(rs.getString("nome"));
    lista.add(p);
}

Having a list of objects Perfil defined, you can use this class I developed some time ago, which can be used as a ComboBoxmodel generic for any type of object received:

public class GenericComboModel<E> extends AbstractListModel<E> implements ComboBoxModel<E>{

    private List<E> itemList;
    private E selection;

    public GenericComboModel(List<E> list) {
        this.itemList = list;
    }

    @Override
    public int getSize() {
        return this.itemList.size();
    }

    @Override
    public E getElementAt(int index) {
        return this.itemList.get(index);
    }

    @Override
    public Object getSelectedItem() {
        return this.selection;
    }

    @Override
    public void setSelectedItem(Object anItem) {
        this.selection = (E) anItem;
    }
}

To use, after the list is popular, just configure the above class as combo model, passing the list and parameterizing the object that the class will handle in the list:

cbPerfil.setModel(new GenericComboModel<Perfil>(lista));

To redeem the option selected at some point from the code:

Perfil pSelected = (Perfil)cbPerfil.getSelectedItem();

This will rescue a Perfil, and to get the id just call pSelected.getId().

Browser other questions tagged

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