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.
You want to do something when a jcombobox option is selected?
– user28595
Yes ! I want to assign a value to a variable according to combo items
– Daniel Santos
Code snippet?! Have you done anything yet?!
– StillBuggin