All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.alantea.swing.action.SelectionManager Maven / Gradle / Ivy

The newest version!
package net.alantea.swing.action;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.alantea.liteprops.ChangeListener;

public class SelectionManager implements ChangeListener
{
   private Map, List>> selectionListeners = new HashMap<>();

   @Override
   public void changed(Object oldValue, Object newValue)
   {
      if (newValue != null)
      {
         Class cl = newValue.getClass();
         List> listeners = selectionListeners.get(newValue.getClass());
         while ((listeners == null) && (cl != null))
         {
            listeners = selectionListeners.get(cl);
            if (listeners == null)
            {
               cl = cl.getSuperclass();
            }
         }
         if (listeners != null)
         {
            for (ChangeListener listener : listeners)
            {
               listener.changed(oldValue, newValue);
            }
         }
      }
   }

   
   public void addSelectionListener(Class targetClass, ChangeListener listener)
   {
      if ((targetClass != null) && (listener != null))
      {
         List> listeners = selectionListeners.get(targetClass);
         if (listeners == null)
         {
            listeners = new LinkedList<>();
            selectionListeners.put(targetClass, listeners);
         }
         if (!listeners.contains(listener))
         {
            listeners.add(listener);
         }
      }
   }
   
   public void removeSelectionListener(ChangeListener listener)
   {
      if (listener != null)
      {
         for (Class targetClass : selectionListeners.keySet())
         {
            List> listeners = selectionListeners.get(targetClass);
            if ((listeners != null) && (listeners.contains(listener)))
            {
               listeners.remove(listener);
            }
         }
      }
   }
   
   public void removeSelectionListener(Class targetClass, ChangeListener listener)
   {
      if ((targetClass != null) && (listener != null))
      {
         List> listeners = selectionListeners.get(targetClass);
         if ((listeners != null) && (listeners.contains(listener)))
         {
            listeners.remove(listener);
         }
      }
   }
}