I believe that the most recommended option in this case is to use a customized version of a ComboBoxModel
. Except for that, you also need to create a POJO this table Perfil
, something more or less 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()
that sobrescrevi (as was done in this response) is that the name is displayed of the profile 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 part of the database, and not delegate it to class that builds the screen, but as it was not presented any screen detail, I'm going to rely on the method of the question. You must retrieve the data from your table and assign the class above, creating a list of all the items in the database:
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
set, you can use this class that worked out for some time, 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 popular list, just set up as the class of the combo model, through the list and parameterize the object that the class will address in the list:
cbPerfil.setModel(new GenericComboModel<Perfil>(lista));
To redeem the selected option at some point in the code:
Perfil pSelected = (Perfil)cbPerfil.getSelectedItem();
This will retrieve a Perfil
, and to get the id just call pSelected.getId()
.