Search code examples
javaswingactionlistenerjcheckboxitemlistener

Creating multiple JCheckBox with multiple ActionListener


I made this sample below to simulate multiple JCheckBox creation and its Action Listener.

int global=0;

//some code

JCheckBox[] checkBox = new JCheckBox[2];

        for(int i = 0; i <=1; i++){

        checkBox[i] = new JCheckBox(strings[i]);
        panel.add(checkBox[i]);

          checkBox[i].addItemListener(new ItemListener() {

                @Override
                public void itemStateChanged(ItemEvent evt) {
                    if (evt.getStateChange() == ItemEvent.SELECTED){
                        JOptionPane.showConfirmDialog(null, "Message"+global);
                    }
                }
            });                                                             
          global++;
        }

What I'm not getting is that my output for the Dialog is always "Message 2". In my logic if I'm declaring one AddItemListener for each checkBox, I should recieve two different dialogs for each checked box, such as "Message 1" and "Message 2". What am I doing wrong here? How to handle this please?

Thanks in advance


Solution

  • When showConfirmDialog() is first called global has already value 2. If you want different message for each check-box try putting global++ (will increment at each call) right before JOptionPane.showConfirmDialog(null, "Message"+global); and this will make it more clear to you.

    if I'm declaring one AddItemListener for each checkBox, I should recieve two different dialogs for each checked box, such as "Message 1" and "Message 2"

    Why do you think you should get two (different) invocations of listener method per checkbox if you know that you have only one listener per checkbox?

    One of the more possible solutions could be to implement your own ItemListener which has stored the message (or just number) to be shown in its instance variable.