I´m trying to validate dynamically an item selected by a JComboBox, and I want to cancel the selection change in case the validation is not correct. Is there any way to achieve it?
private ItemListener itemListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if (true) CANCEL_CHANGE;
}
}
};
I tried to define a var holding the old value, unregistering listener, and select to previous state manually, but then the problem comes with the first change, because the var is not initialized and there´s no way hold the original value.
I also tried using ActionListener, but found no way to programtically cancel the change, and I don´t need fire event then there´s no change but I am assessing the chance of setSelection manually, so I revert to ItemListener.
I can do that, dunno why you cannot do it. Have a look at this code example, select three times any values, then on the fourth time it will revert back to empty string :
Code with Previous Value