Jcombobox within a JOptionPane

0

Good morning, I have a list of some reasons

 private List<Motivo> motivos;

I need to populate a jComboBox with this list and get the selected option.

Currently I have done with MessageDialog where I can fill normally but I can not get the selected item, for example:

 JComboBox jcb = new JComboBox();
    for (Motivo motivos_bloqueia : motivos) {
        jcb.addItem(motivos_bloqueia.getMotivo());

    }

JOptionPane.showMessageDialog(null, jcb, "Selecione o motivo", JOptionPane.QUESTION_MESSAGE);

But this way I can not get the selected item.

I read in some forums where I was directed to use an InputDialog instead of MessageDialog, as follows:

Object[] opcoes = {"Um","Dois","Tres","Quatro"};
Object res = JOptionPane.showInputDialog(null, "Escolha um item" , "Selecao
de itens" ,
JOptionPane.PLAIN_MESSAGE , null ,opcoes,"");

That way I would have the item selected in the 'res' variable. The problem is that the parameter that it passes to the combobox add the items in the options is an Object [] and in case what I have is a List.

How do I get the item that the user selected in the combobox by clicking OK?

    
asked by anonymous 18.07.2016 / 15:03

2 answers

2

A JOptionPane does not return the contents of a component inserted in it, such as a combobox, since each component already has all the methods necessary for its content to be manipulated. In the case of JComboBox , I think there is a mistake, you will not get the item selected by JOptionPane , you must call getSelectedItem() of the component itself to get this. Here's an example below, using your code:

JComboBox jcb = new JComboBox();

for (int i = 0; i < 6; i++) {
    jcb.addItem("motivo 0" + (i + 1));
}

JOptionPane.showMessageDialog(null, jcb, "Selecione o motivo", JOptionPane.QUESTION_MESSAGE);

JOptionPane.showMessageDialog(null, jcb.getSelectedItem(), "Opção selecionada", JOptionPane.INFORMATION_MESSAGE);
    
18.07.2016 / 15:18
1

The question is not very clear. You seem to want something to happen when you click the button. In this case, use OptionDialog , which returns a int and, from the returned value, do something.

    JComboBox jcb = new JComboBox();
        for (Motivo motivos_bloqueia : motivos) {
            jcb.addItem(motivos_bloqueia.getMotivo());

        }

    int selecionado = JOptionPane.showOptionDialog(null, jcb, "Selecione o motivo", JOptionPane.QUESTION_MESSAGE);

    if (selecionado == 1) {
        //faça algo
    }

Note that you can use ENUM if your list of reasons is previously known. It will be enough to assign each value of ENUM a int equivalent.

    
18.07.2016 / 15:22