Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 930
Victor R. Oliveira Avatar asked Apr 18 '26 14:04

Victor R. Oliveira


1 Answers

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.

like image 53
ps-aux Avatar answered Apr 20 '26 03:04

ps-aux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!