1

I'm trying to write an undo manager for JToggleButtons (specifically JCheckBoxes). Each check box has an item listener that adds a new edit to an undo manager. However, when I try to undo the selection, the setSelected(boolean) method triggers the item listener, adding the undo as another UndoableEdit, so undos can be made indefinitely. My workaround to this problem was this:

ItemListener[] ils = button.getItemListeners();
Arrays.stream(ils).forEach(button::removeItemListener);
button.setSelected(wasSelected);
Arrays.stream(ils).forEach(button::addItemListener);

This works, but seems a bit messy. Is there a better way to do this?

ricky3350
  • 1,710
  • 3
  • 20
  • 35
  • That way has worked well for me. – Hovercraft Full Of Eels Mar 05 '16 at 14:28
  • 4
    Another option is to use a boolean flag variable, but that will only work for listeners that you yourself have control over. e.g., set the flag to false before changing the selected state, and then changing to true afterwards, and use the flag inside of the listener to decide whether to respond to the state change or not. – Hovercraft Full Of Eels Mar 05 '16 at 14:30

0 Answers0