package com.onaro.util.jfc.enumeration; import java.io.*; import java.util.*; public class EnumSetWithEvents> implements Serializable { private static final long serialVersionUID = 1L; private transient LinkedHashSet> listeners; private EnumSet selectedEnums; private transient boolean isAdjusting = false; public EnumSetWithEvents(EnumSet selectedEnums) { this.selectedEnums = selectedEnums; } public boolean contains(K enumValue) { return selectedEnums.contains(enumValue); } public void add(K enumValue) { selectedEnums.add(enumValue); fireEnumSelectionChanged(enumValue, true); } public synchronized void remove(K enumValue) { selectedEnums.remove(enumValue); fireEnumSelectionChanged(enumValue,false); } //synchronized so the list of listeners will not change while the list is iterated private void fireEnumSelectionChanged(K enumValue, boolean selected) { if (listeners != null) { EnumSelectionEvent evt = new EnumSelectionEvent(this, enumValue, selected, isAdjusting); for (EnumSelectionListener listener : listeners) { listener.selectionChanged(evt); } } } //synchronized so the list of listeners will not change while the list is iterated public synchronized void addEnumSelectionListener(EnumSelectionListener listener) { if(listeners == null){ listeners = new LinkedHashSet>(); } listeners.add(listener); } //synchronized so the list of listeners will not change while the list is iterated public synchronized void removeEnumSelectionListener(EnumSelectionListener listener) { listeners.remove(listener); } private void startAdjusting() { isAdjusting = true; } private void stopAdjusting() { isAdjusting = false; //fire an event for all the changes together fireEnumSelectionChanged(null,false); } public EnumSet toSet() { return selectedEnums; } /** * set enumValue to be the only selected enum * @param enumValue the only enum to be selected */ public void set(K enumValue) { //avoid from firing multiple events startAdjusting(); //first, make sure that all the other enums are not selected EnumSet othersSelected = selectedEnums.clone(); othersSelected.remove(enumValue); for(K enumValuesToRemove: othersSelected){ remove(enumValuesToRemove); } //add the enumValue if it's not already selected if(!contains(enumValue)) { add(enumValue); } //fire one event to summarize all the changes stopAdjusting(); } public void set(EnumSet enumValues) { //avoid from firing multiple events startAdjusting(); selectedEnums.clear(); selectedEnums.addAll(enumValues); //fire one event to summarize all the changes stopAdjusting(); } public String toString() { return String.valueOf(selectedEnums); } }