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