How to set index when inserting item in JComboBox?

3

I wonder if anyone could help me. I'm trying to add items to a JComboBox :

Pessoa carlos = new Pessoa(12, "Carlos" , 0.0f);
jComboBoxF.addItem(carlos.getNome());
Pessoa maria = new Pessoa(23, "Maria" ,0.0f);
jComboBoxF.addItem(maria.getNome());

In this case the JComboBox is in the index "0" as the value "Carlos", and in index "1" with the value Maria.

What I liked to know was if adding the name was also possible to add the index, in order to be in this case with two identifiers 12 and 23, 12 for the value Carlos and 23 for the value Maria.

In other words, I want to use People's id's as an index of JComboBox .

What I mean by this is to use the index of JComboBox to identify the Person in question, since the index of the combo in this way would be the Person's own ID.

    
asked by anonymous 23.07.2015 / 20:31

3 answers

2

André ,

If you are using model on your JComboBox that implements interface MutableComboBoxModel you will be able to do:

((MutableComboBoxModel) jComboBox.getModel()).insertElementAt(carlos, 0);
((MutableComboBoxModel) jComboBox.getModel()).insertElementAt(maria, 1);

But I strongly advise you to create the list of items before putting in your JComboBox , something like:

List<Pessoa> pessoas = new ArrayList<>();
pessoas.add(new Pessoa(12, "Carlos" , 0.0f));//adicionando o carlos na lista
pessoas.add(new Pessoa(23, "Maria" ,0.0f));

//com a lista pronta, altere o model no seu jComboBox
jComboBox.setModel(new DefaultComboBoxModel<>(pessoas.toArray()));

When you say you want the index to be 12 or 23, this is only possible if you have more than 23 items in your jComboBox . The index in the case is the position that the element is in its jComboBox , where 0 is the first position up to list size -1.

What you might want is to display these numbers next to the name in your jComboBox . For this you only need to override the toString() method in your Pessoa class.

public class Pessoa{

  private String nome;
  private int idade;

  @Override
  public String toString(){
    return idade + " - " + nome;
  }

}

So your jComboBox will display the items like this:

  • 12 - Carlos
  •   
  • 23 - Maria
23.07.2015 / 21:01
1

Here's a working example of what you want. Basically the key is to implement the toString() method properly.

package testes;

import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class TesteComboBox {
    public static void main(String[] args) {
        EventQueue.invokeLater(TesteComboBox::exemplo);
    }

    private static void exemplo() {
        JFrame jf = new JFrame("Exemplo");
        JComboBox<Pessoa> jComboBoxF = new JComboBox<>();
        jf.setLayout(new FlowLayout());
        jf.add(jComboBoxF);

        Pessoa carlos = new Pessoa(12, "Carlos", 0.0f);
        Pessoa maria = new Pessoa(23, "Maria", 0.0f);
        jComboBoxF.addItem(carlos);
        jComboBoxF.addItem(maria);

        JButton mensagem = new JButton("Mostrar");
        jf.add(mensagem);
        mensagem.addActionListener(e -> {
            int idx = jComboBoxF.getSelectedIndex();
            if (idx == -1) {
                JOptionPane.showMessageDialog(jf, "Você não escolheu ninguém.");
            } else {
                Pessoa escolha = jComboBoxF.getItemAt(jComboBoxF.getSelectedIndex());
                JOptionPane.showMessageDialog(jf, "Você escolheu " + escolha.getNome() + " de id " + escolha.getId());
            }
        });

        jf.pack();
        jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        jf.setVisible(true);
    }

    public static class Pessoa {
        private final int id;
        private final String nome;
        private final double outraCoisa;

        public Pessoa(int id, String nome, double outraCoisa) {
            this.id = id;
            this.nome = nome;
            this.outraCoisa = outraCoisa;
        }

        public int getId() {
            return id;
        }

        public String getNome() {
            return nome;
        }

        public double getOutraCoisa() {
            return outraCoisa;
        }

        @Override
        public String toString() {
            return getNome();
        }
    }
}

If the object you want to add in the combobox can not have an appropriate toString() method, then use an auxiliary class with toString() suitable:

public class MinhaClasseAuxiliar {
    private final Pessoa p;
    public MinhaClasseAuxiliar(Pessoa p) {
        this.p = p;
    }

    public Pessoa getPessoa() {
        return p;
    }

    @Override
    public String toString() {
        // Aqui você faz o que quiser.
    }
}

And then you add auxiliary class objects instead of adding Pessoa .

    
23.07.2015 / 21:16
0

I understood your doubt! But I do not know if that's going to work for you after all this time, but it can suddenly work for someone else. This link has something that can serve you: link

    
13.04.2016 / 03:28