eeijlar
eeijlar

Reputation: 1342

Can't get ItemListener to work for JCheckBox

I am using this code to create a JCheckBox

private final JCheckBox cbDisplayMessage = new JCheckBox("Display");

        cbDisplayMessage.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getItemSelectable() == cbDisplayMessage) {
                  if(cbDisplayMessage.isSelected()) { 
                     cbDisplayMessage.setSelected(false); 
                  } else {
                     cbDisplayMessage.setSelected(true); 
                  }


            }
        }
    });

When I run this it causes an StackOverflow error on setSelected(true). Can't figure out what I am doing wrong. Any ideas appreciated....

Upvotes: 0

Views: 219

Answers (2)

Braj
Braj

Reputation: 46841

You can try with ActionListener instead of ItemListener as shown below without causing StackOverflow error.

cbDisplayMessage.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        if (cbDisplayMessage.isSelected()) {
            cbDisplayMessage.setSelected(false);
        } else {
            cbDisplayMessage.setSelected(true);
        }
    }
});

There is no need to check the source of the event again because you are sure that you have added this listener on the same object. This is required only if same listener is added for more components.


-- EDIT--

Now Your requirement is clear to me. If you want to toggle the state of the check box then there is no need to do it using listener because that's the default behavior of the check box.

Upvotes: 1

Josh
Josh

Reputation: 1553

Your listener is called every time the state changes, but you trigger a new state change from within that listener, so each state change results in that listener being called over and over again until your stack is full. Your setup has to be a bit more complicated to do something like that - if you want to change the state of the component you're listening to, you'll want to remove its listener(s), fire your programmatic state change, then re-add them.

Upvotes: 0

Related Questions