Perform actions from the selected item in Jcombobox

Asked

Viewed 1,603 times

2

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

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

  • You want to do something when a jcombobox option is selected?

  • Yes ! I want to assign a value to a variable according to combo items

  • Code snippet?! Have you done anything yet?!

1 answer

3


Just perform the desired action within the method itemStateChanged:

seuJCombo.addItemListener(new ItemListener() {

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

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

Once confirmed that the item has been selected, just treat 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
                }
            }
        });

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

  • Thanks guy ! But so, I did not understand where I have to put my combo item '-'

  • @Danielsantos see if the issue answers you.

  • 4

    It would be interesting for downvote to inform me what is wrong with the question, so I can correct it, because I could not notice any error.

  • Thanks a lot, man! Now I get it !

Browser other questions tagged

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