0

I have the following listeners:

        mListener = new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (((JCheckBox) e.getSource()).isSelected()) {
                    setRequired(true);
                } else {
                    setRequired(false);
                }
                getTableSteps().repaint();
            }
        };

        myCheckBox.addItemListener(mListener);

        for (int i = 0; i < mTableSteps.getRowCount(); i++) {
            ((JCheckBox) mTableSteps.getCellRenderer(i, 0)).addItemListener(new ItemListener() {

                public void itemStateChanged(ItemEvent e) {
                    myCheckBox.setSelected(false);
                }
            });
        }

As you can see, myCheckBox is the checkbox which if it is modified, modifies some of the checkboxes from the first column of mtablesteps (this is done in the setRequired method). Also, if one of the checkboxes from mtablesteps column 0 are modified they should put myCheckBox to not being selected.

Now the problem is when I first select myCheckBox it triggers the listener and selects some checkboxes from mTableSteps. But when these checkboxes are selected, they also trigger their listener and deselect myCheckBox. Thus, myCheckBox always gets deselected.

I hope this makes sense. Any suggestions on how to avoid this are appreciated.

To be more even more clear, what I'm trying to achieve is have a listener for myCheckBox which when the checkbox is selected it will select some of the checkboxes from the first column of mTableSteps. But also, if I select/deselect a checkbox from the table, it will put myCheckBox to not selected. Thanks a lot.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Fofole
  • 3,398
  • 8
  • 38
  • 59

1 Answers1

0

You need some kind of state flag that you can use to tell the child listeners if they should process the event of not.

mListener = new ItemListener() {

    public void itemStateChanged(ItemEvent e) {
        ignoreUpdates = true
        try {
            if (((JCheckBox) e.getSource()).isSelected()) {
                setRequired(true);
            } else {
                setRequired(false);
            }
            getTableSteps().repaint();
        } finally {
            ignoreUpdates = false;
        }
    }
}

myCheckBox.addItemListener(mListener);

for (int i = 0; i < mTableSteps.getRowCount(); i++) {
    ((JCheckBox) mTableSteps.getCellRenderer(i, 0)).addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (!ignoreUpdates) {
                myCheckBox.setSelected(false);
            }
        }
    });
}

Hope that helps

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366