Search code examples
javaswingjoptionpanejcheckbox

JCheckbox changes state twice when I show a dialog on statechange, how to fix?


I have a checkbox that, when the user selects it, should spawn a dialog with further info, and upon reaction from the user, do something. My code looks basically like this:

private void onItemStateChanged(java.awt.event.ItemEvent evt) {
    System.out.println("STATE CHANGED!");//TODO debug code
    if (evt.getStateChange() == ItemEvent.SELECTED) {
        int returnVal = JOptionPane.showConfirmDialog(this, "blablatext");
        if (returnVal == JOptionPane.OK_OPTION) {
            this.field1TF.setText("");
            this.field1TF.setEditable(false);
            this.field2TF.setText("");
            this.filed2TF.setEditable(false);
        }else if(returnVal == JOptionPane.NO_OPTION){
            this.field1TF.setText("");
            this.field1TF.setEditable(false);
            this.field2TF.setText("");
            this.field2TF.setEditable(false);
        }
    } else if(evt.getStateChange() == ItemEvent.DESELECTED){
        this.field1TF.setEditable(true);
        this.field2TF.setEditable(true);
    }
}

My problem now is, that my checkbox changes state always twice when I click on it. It somehow has to do with the JOptionPane.showConfirmDialog because if I comment that out, it works as intended. Am I not aware of something simple I should care about here, or what do I have to do to get my desired reaction? (User clicks checkbox -> is asked a question -> chooses YES/NO/Cancel -> program acts accordingly)


Solution

  • change that to the ActionListener

    JCheckBox http://download.oracle.com/javase/tutorial/uiswing/components/button.html#checkbox

    ActionListener http://download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html