How to set index when inserting item in Jcombobox?

Asked

Viewed 1,552 times

3

I wonder if someone 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 the index "1" with the value Maria.

What I would like to know is whether 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 the People id’s as the JComboBox.

What I want with 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.

  • Will Carlos always be the thirteenth item of Jcombobox? Will Mary always be the twenty-fourth in the list? Or does the list have only these elements even?

  • In this case Jcombobox would only have two elements, Carlos and Maria. Your Index are 0 and 1 and I would like to be able to choose when inserting for example 12 and 23.

  • So it seems to me that you don’t understand what the index of JComboBox I mean. It’s like an array, index 0 is the first item, index 1 is the second item, index 2 is the third item... And that’s not going to work if you want to have just two items with Dexe 12 and 23. I believe that what you really want is to retrieve that number that’s inside the person’s object, which is exactly what I showed you with my answer, because by what you describe their position and order in JComboBox is not relevant to you, only the number you have associated with each Person is.

  • I know how the index works and what its importance, was in doubt is if there would be any way to manipulate the index and we have come to the conclusion that not. The problem is solved by placing the object in Jcombobox and not just the name in order to access all attributes of the object. Thank you very much, problem solved.

3 answers

2

André,

if you are using a model in his JComboBox that implements the interface MutableComboBoxModel you’ll manage to make:

((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, it will only be possible if you have more than 23 items in your jComboBox. The index in the case is the position the element is in its jComboBox, 0 being the first position up to list size -1.

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

public class Pessoa{

  private String nome;
  private int idade;

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

}

So yours jComboBox will display the items like this:

  • 12 - Carlos
  • 23 - Mary
  • Thanks for the reply and the tip. My goal is not to present in the combo more than the name of the person. That’s not what I mean. My idea was to use people’s id’s as jcombox index so that when choosing an item I could use the combo index to identify the Person in question. I just don’t know if it’s possible and if possible I don’t know how to do it. Thank you very much.

  • Oh yes. But then you will have to ensure that your people have growing id’s, that there is none missing and all these people are in the jComboCox. Just sort the list and put it on it. In case you would have to have id’s from 0... to 24 to be able to use index 12 and 23.

  • Yeah, so I can’t do what I want. So I know how to do it... I’ll have to think of another way. Thank you very much

  • When using " jComboBox.setModel(new Defaultcomboboxmodel<>(people.toArray()); "the combo presents anything as "namepackages. Persons@umnumero" :)

  • It overwrote the toString() of your Person class? It will display what you put to return on toString() , if not overwriting displays the memory address

1

Here is a functional example of what you want. Basically the secret is to implement the method toString() adequately.

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 on the combobox cannot have a method toString() suitable, so use an auxiliary class with the 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 tweaks from the auxiliary class instead of adding Pessoa.

  • Thank you very much for the answer. That’s not quite what I intend. I have already edited the question in order to clarify the doubt better. But thanks in advance for the tips.

0

  • Where this adds an item by changing the index of the combobox??

  • Friend, look at the link, there it is clearer the answer! It is in c#, but can understand and apply in java the suggested logic.

  • 1

    If the answer depends on the link to make sense, then it is not a good answer. The link should be only complement, not have the solution. The code also does not do what asked in the question. If you have more information on the link that might solve the question, I suggest you add it, as this code does not solve the problem. Not to mention that this code seems to be in C# and the language of pegunta is java!

  • Okay, thanks for the considerations!

  • You can’t apply this in java, the operation of the Forms window and swing is not nearly similar.

  • I applied and it worked for me.

  • Look at the other answers, the logic of your code doesn’t even look like the other ones. It’s just a hint, if the question is from one language, avoid posting solution in another unless the user who asked make it clear in the question.

Show 2 more comments

Browser other questions tagged

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