Search code examples
javaswingjcomboboxitemlistener

Change JComboBox selection on the basis of user confirmation


Is there any way to keep user on old selected option from JComboBox. There is one confirmation I am asking to user when he/she wan't to change JComboBox's selected item, if user say yes, then only I want to keep new selection else set old item selected.

Is there any way to restrict JComboBox selection? I am using ItemListener and MouseListener to achieve above functionality.


Solution

  • ItemListener generally fires two events. The first is a DSESELECTED event (the old value) and a SELECTED event (the new value).

    You could monitor these changes, recording the DESELECTED value as they occur

    As a test, you could try something like this...

    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            System.out.println("Selected :" + e.getItem());
        } else if (e.getStateChange() == ItemEvent.DESELECTED) {
            System.out.println("Deselected :" + e.getItem());
        }
    }
    

    If the user selects "no" to the change, you could restore the DESELECTED value...