Fill Jcombobox with an object

Asked

Viewed 2,360 times

7

I would like a help to fill one JComboBox with a class. In this class, return two parameters: Id and Desc.

Category class I need to show in combo:

private int Id_categoria;
private String Desc_Categoria;

How do I show only the Desc_categoria? And in time to select some value, as I only catch the Id_Categoria?

I’ve tried, pass as parameter in JComboBox an array of category type and also add a model.

  • What have you tried to do? Add to question.

  • How do you get these values? You want to display only one or several values?

  • I receive the values of the database and create an arrayList of categories, I would like to display this list

2 answers

6


Another solution would be to use the comboModel. Simple example:

public class AulaComboModel extends AbstractListModel<Aula> implements ComboBoxModel<Aula> {

    private List<Aula> lista;

    /* Seleciona um objeto na caixa de seleção */
    private Aula selecionado;

    /* Método construtor */
    public AulaComboModel() {
        /* Popula a lista */
        popular();

        /* Define o objeto selecionado */
        setSelectedItem(lista.get(0));
    }

    /* Captura o tamanho da listagem */
    public int getSize() {
        int totalElementos = lista.size();
        return totalElementos;
    }

    /* Captura um elemento da lista em uma posição informada */
    public Aula getElementAt(int indice) {
        Aula t = lista.get(indice);
        return t;
    }

    /* Marca um objeto na lista como selecionado */
    public void setSelectedItem(Object item) {
        selecionado = (Aula) item;
    }

    /* Captura o objeto selecionado da lista */
    public Object getSelectedItem() {
        return selecionado;
    }

    private void popular() {
        try {
            /* Cria o DAO */
            AulaDAO tdao = new AulaDAO();

            /* Cria um modelo vazio */
            Aula t = new Aula();
            t.setNomeUsuario("");

            /* Recupera os registros da tabela */
            lista = tdao.buscar(t);

            /* Cria o primeiro registro da lista */
            Aula primeiro = new Aula();
            primeiro.setIdUsuario(0);
            primeiro.setNomeUsuario("--SELECIONE UM USUARIO--");

            /* Adiciona o primeiro registro a lista */
            lista.add(0, primeiro);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

In that comboModel I retrieve the bank records as follows: lista = tdao.buscar(t);

To implement this comboModel you need to override the method equals and the toString

Do this on the model, example:

 @Override
 public String toString() {
        String texto = idUsuario+" - "+ nomeUsuario;
        return texto;
    }

  @Override
   public boolean equals(Object obj) {
       Aula f = (Aula) obj;
       return Objects.equals(this.idUsuario, f.idUsuario);
   }

Note that in the toString i am concatenating id and name.

If using netbeans go to comboModel component, right-click and go to properties > model > custom code and then install the model created: new AulaComboModel()

inserir a descrição da imagem aqui

This would be a somewhat "bigger" solution to your problem, but the use of comboModel can facilitate and make your code more organized.

inserir a descrição da imagem aqui

  • But the class responsible for displaying the Jcombobox is not the Defaullistcellrenderer?

  • Yes, but the template (fill-in) can be made by AbstractListModel

  • Oh ta, I didn’t even know. I always create a separate model and a different Nderer.

  • I did it that way too, so a friend taught me to do it that way. In the documentation there are some examples as well. https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html

5

Solution 1

In your custom class, add the method toString() in order to return the parameter Desc_Categoria:

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

Solution 2

You can customize the display of Jcombobox through the method getListCellRendererComponent, class Defaultlistcellrenderer:

DefaultListCellRenderer renderer = new DefaultListCellRenderer() {

            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                  if (value instanceof SuaCustomClasse) {
                    SuaCustomClasse minhaclasse = (SuaCustomClasse) value;
                    setText(minhaclasse.getDesc_Categoria);//supondo que seu parametro seja encapsulado
                }
                return this;
            }

...

   combo.setRenderer(renderer);

This way, you’re changing like the JCombobox displays the elements added to it. You can create a ListCellRenderer customized as well, but it depends on the need and complexity of the objects that will be added to your combobox.

Browser other questions tagged

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