Execute actions from the selected item in JComboBox

1

I wanted to assign value to another class, whichever is selected in JComboBox . For example, if the "Active" item in a combo is selected I wanted to assign a value to a string of an external class if the user had put the combo item "Idle" idem. How do I know which of the two items are selected?

NOTE: Use the name cmbStatus as the name of JComboBox , where there are only two items: "Active" and "Inactive"

    
asked by anonymous 13.03.2016 / 21:29

1 answer

3

Just perform the desired action within the itemStateChanged :

seuJCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                // 
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    //ação aqui
                }
            }
       });

Basically you are creating a listener that will be monitoring selection changes in JComboBox , and when there is a change, if checks if the item's status is "selected".

Once you confirm that the item has been selected, simply handle the selected option using e.getItem() ":

seuJCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                // 
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    //pegando o texto do item selecionado
                    String valorSelecionado = e.getItem().toString();
                    if(valorSelecionado.equals("ativo")){
                        //altere aqui quando ativo selecionado
                  }else{
                   //altere aqui quando inativo selecionado
                }
            }
        });
  

Note: e.getItem() returns a type Object , so it is necessary to cast for the expected type in JComboBox , in the case of   For example, only the text of the selected option is expected,   made cast to String .

    
13.03.2016 / 21:37