Index: LegendManager.java
===================================================================
--- LegendManager.java	(revision 43391)
+++ LegendManager.java	(revision 43392)
@@ -28,32 +28,29 @@
 import java.awt.Component;
 import java.awt.Dimension;
 import java.awt.FlowLayout;
+import java.awt.Point;
+import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Enumeration;
+import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.Iterator;
-import java.util.List;
+import java.util.Map;
 import java.util.prefs.Preferences;
+import javax.swing.Action;
 
 import javax.swing.ImageIcon;
 import javax.swing.JButton;
-import javax.swing.JComponent;
-import javax.swing.JFileChooser;
 import javax.swing.JLabel;
+import javax.swing.JMenuItem;
 import javax.swing.JOptionPane;
 import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
 import javax.swing.JScrollPane;
 import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.JTree;
-import javax.swing.filechooser.FileFilter;
 import javax.swing.tree.DefaultMutableTreeNode;
 import javax.swing.tree.DefaultTreeCellRenderer;
 import javax.swing.tree.DefaultTreeModel;
@@ -66,12 +63,7 @@
 
 import org.gvsig.andami.PluginServices;
 import org.gvsig.andami.messages.NotificationManager;
-import org.gvsig.app.ApplicationLocator;
-import org.gvsig.fmap.geom.Geometry;
-import org.gvsig.fmap.mapcontext.MapContextLocator;
-import org.gvsig.fmap.mapcontext.MapContextManager;
 import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
-import org.gvsig.fmap.mapcontext.exceptions.WriteLegendException;
 import org.gvsig.fmap.mapcontext.layers.FLayer;
 import org.gvsig.fmap.mapcontext.layers.FLayers;
 import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
@@ -80,14 +72,9 @@
 import org.gvsig.fmap.mapcontext.rendering.legend.IClassifiedVectorLegend;
 import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
 import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
-import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendReader;
-import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendWriter;
-import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
-import org.gvsig.i18n.Messages;
+import org.gvsig.symbology.SymbologyLocator;
 import org.gvsig.symbology.swing.SymbologySwingLocator;
 import org.gvsig.symbology.swing.SymbologySwingManager;
-import org.gvsig.tools.ToolsLocator;
-import org.gvsig.tools.persistence.PersistenceManager;
 
 /**
  * Implements the panel which allows the user to control all the information
@@ -98,21 +85,46 @@
  *
  * @author jaume dominguez faus - jaume.dominguez@iver.es
  */
-public class LegendManager extends AbstractThemeManagerPage {
+public class LegendManager extends AbstractThemeManagerPage implements LegendsPanel {
 
     private static final Logger logger =
         LoggerFactory.getLogger(LegendManager.class);
 
     private static final long serialVersionUID = 7989057553773181019L;
-//    private static ArrayList<Class<? extends ILegendPanel>> legendPool =
-//        new ArrayList<Class<? extends ILegendPanel>>();
-    // private static ArrayList<Class<? extends IFMapLegendDriver>>
-    // legendDriverPool = new ArrayList<Class<? extends IFMapLegendDriver>>();
 
+    public static class Pages implements Iterable<ILegendPanel> {
+
+        private Map<Class<? extends ILegendPanel>, ILegendPanel> pages;
+
+        public Pages() {
+            this.pages = new HashMap<>();
+        }
+        
+        public void add(ILegendPanel page) {
+            this.pages.put(page.getClass(), page);
+        }
+
+        public Iterator<ILegendPanel> iterator() {
+            return this.pages.values().iterator();
+        }
+
+        public boolean contains(Class<? extends ILegendPanel> pageClass) {
+            return this.pages.containsKey(pageClass);
+        }
+
+        public ILegendPanel get(Class<? extends ILegendPanel> pageClass) {
+            return this.pages.get(pageClass);
+        }
+
+        public Collection<ILegendPanel> asCollection() {
+            return this.pages.values();
+        }
+    }
+
     private FLayer layer;
-    private ILegend legend; // Le asignaremos la leyenda del primer tema activo.
-    private Hashtable<Class<? extends ILegendPanel>, ILegendPanel> pages =
-        new Hashtable<Class<? extends ILegendPanel>, ILegendPanel>();
+    private ILegend legend; 
+    private Pages pages = new Pages();
+    
     private JPanel topPanel = null;
     private JTextArea titleArea = null;
     private JPanel preview = null;
@@ -120,421 +132,26 @@
     private JTree jTreeLegends;
     private ILegendPanel activePanel;
     private JScrollPane legendTreeScrollPane;
-    private boolean dirtyTree_;
-    private DefaultMutableTreeNode root = new DefaultMutableTreeNode();
+//    private boolean dirtyTree_;
+    private final DefaultMutableTreeNode root = new DefaultMutableTreeNode();
     private DefaultTreeModel treeModel;
     private JScrollPane jPanelContainer;
     private JPanel jCentralPanel;
     private JSplitPane jSplitPane;
     private boolean isTreeListenerDisabled;
-    private JButton btnSaveLegend;
-    private JButton btnLoadLegend;
+    private JButton btnOptionalActions;
+    private JPopupMenu menuOptionalActions;
     private Hashtable<FLayer, ILegend> table = null;
     private boolean empty = true;
     private JLabel iconLabel;
 
     public static String defaultLegendFolderPath;
     {
-
         Preferences prefs = Preferences.userRoot().node("gvsig.foldering");
         defaultLegendFolderPath = prefs.get("LegendsFolder", "");
     }
 
-    private ActionListener loadSaveLegendAction = new ActionListener() {
 
-        public void actionPerformed(java.awt.event.ActionEvent e) {
-            JComponent c = (JComponent) e.getSource();
-            if (c.equals(getBtnSaveLegend())) {
-
-                try {
-                    saveLegend();
-                } catch (Exception exc) {
-                    JOptionPane.showMessageDialog(
-                        ApplicationLocator.getManager().getRootComponent(),
-                        Messages.getText("_Unable_to_save_legend")
-                        + "\n\n" + exc.getMessage(),
-                        Messages.getText("legend"),
-                        JOptionPane.WARNING_MESSAGE);
-                    return;
-                }
-
-            } else
-                if (c.equals(getBtnLoadLegend())) {
-                    try {
-                        loadLegend();
-                    } catch (Exception e1) {
-                        JOptionPane.showMessageDialog(
-                            ApplicationLocator.getManager().getRootComponent(),
-                            Messages.getText("_Unable_to_read_legend")
-                            + "\n\n" + e1.getMessage(),
-                            Messages.getText("legend"),
-                            JOptionPane.WARNING_MESSAGE);
-                        return;
-                    }
-                }
-        }
-
-        private void saveLegend() throws Exception {
-
-            List<LegendFileFilter> filters = getLegendFileFilters(true);
-            if (filters.size() == 0) {
-                JOptionPane.showMessageDialog(
-                    ApplicationLocator.getManager().getRootComponent(),
-                    Messages.getText("_No_output_format_available"),
-                    Messages.getText("legend"),
-                    JOptionPane.WARNING_MESSAGE);
-                return;
-            }
-
-            ILegend legend = activePanel.getLegend();
-            MapContextManager mcoman = MapContextLocator.getMapContextManager();
-
-            JFileChooser fileChooser = new JFileChooser();
-            fileChooser.setAcceptAllFileFilterUsed(false);
-
-            for (int i=0; i<filters.size(); i++) {
-                fileChooser.addChoosableFileFilter(filters.get(i));
-            }
-
-            if (fileChooser.showSaveDialog(
-                ApplicationLocator.getManager().getRootComponent())
-                == JFileChooser.APPROVE_OPTION) {
-
-                LegendFileFilter lff = (LegendFileFilter) fileChooser.getFileFilter();
-
-                File selfile = fileChooser.getSelectedFile();
-                if (!selfile.getAbsolutePath().toLowerCase().endsWith(
-                    "." + lff.getFileExtension().toLowerCase())) {
-
-                    selfile = new File(selfile.getAbsolutePath() +
-                        "." + lff.getFileExtension().toLowerCase());
-                }
-
-                ILegendWriter lw = null;
-                lw = mcoman.createLegendWriter(legend.getClass(), lff.getFileExtension());
-
-                if (lw == null) {
-                    throw new WriteLegendException(legend,
-                        new Exception("Unable to create legend writer."));
-                } else {
-                    lw.write(legend, selfile, lff.getFileExtension());
-                }
-            }
-        }
-
-        /**
-         *
-         * @param writing true for writing; false for reading
-         * @return
-         */
-        private List<LegendFileFilter> getLegendFileFilters(boolean writing) {
-
-            List<LegendFileFilter> resp = new ArrayList<LegendFileFilter>();
-            MapContextManager mcoman = MapContextLocator.getMapContextManager();
-            List wformats = null;
-
-            if (writing) {
-                wformats = mcoman.getLegendWritingFormats();
-            } else {
-                wformats = mcoman.getLegendReadingFormats();
-            }
-
-            String fmt = null;
-            for (int i=0; i<wformats.size(); i++) {
-                fmt = (String) wformats.get(i);
-                fmt = getFileExtension(fmt);
-                if (fmt != null) {
-                    resp.add(new LegendFileFilter(fmt));
-                }
-            }
-            return resp;
-        }
-
-
-        /**
-         * Returns null if mime format is not parsed properly
-         *
-         * @param fmt MIME format
-         *
-         * @return
-         */
-        private String getFileExtension(String fmt) {
-            // Example: "text/xml; subtype=gml/2.1.2" => "gml"
-            if (fmt == null) {
-                return null;
-            }
-            String[] parts = fmt.split(";");
-            String aux = "";
-            if (parts.length > 1) {
-                aux = parts[1].trim();
-            } else {
-                aux = parts[0].trim();
-            }
-            parts = aux.split("=");
-            if (parts.length > 1) {
-                aux = parts[1].trim();
-                // Example: aux = "gml/2.1.2"
-                parts = aux.split("/");
-                return parts[0].length() == 0 ? null : parts[0].toLowerCase();
-            } else {
-                aux = parts[0].trim();
-                // Example: "text/xml"
-                parts = aux.split("/");
-                if (parts.length > 1) {
-                    return parts[1].length() == 0 ? null : parts[1].toLowerCase();
-                } else {
-                    return aux.length() == 0 ? null : aux.toLowerCase();
-                }
-            }
-        }
-
-        private void loadLegend() throws Exception {
-
-            List<LegendFileFilter> filters = getLegendFileFilters(false);
-            if (filters.size() == 0) {
-                JOptionPane.showMessageDialog(
-                    ApplicationLocator.getManager().getRootComponent(),
-                    Messages.getText("_No_input_format_available"),
-                    Messages.getText("legend"),
-                    JOptionPane.WARNING_MESSAGE);
-                return;
-            }
-
-            JFileChooser fileChooser = new JFileChooser();
-            fileChooser.setAcceptAllFileFilterUsed(false);
-
-            for (int i=0; i<filters.size(); i++) {
-                fileChooser.addChoosableFileFilter(filters.get(i));
-            }
-
-            // open a file
-            if (fileChooser.showOpenDialog((Component) PluginServices
-                .getMainFrame()) == JFileChooser.APPROVE_OPTION) {
-
-                File file = fileChooser.getSelectedFile();
-                LegendFileFilter lff = (LegendFileFilter) fileChooser.getFileFilter();
-                MapContextManager mcoman = MapContextLocator.getMapContextManager();
-                ILegendReader lr = mcoman.createLegendReader(lff.getFileExtension());
-
-                ILegend leg = lr.read(file, Geometry.TYPES.GEOMETRY);
-                applyLegend(leg);
-            }
-        }
-    };
-
-    //
-    // JLegendFileChooser jfc = new
-    // JLegendFileChooser(getLegendDrivers(),true);
-    // jfc.setAcceptAllFileFilterUsed(false);
-    //
-    //
-    // File basedir = null;
-    // jfc.setCurrentDirectory(basedir);
-    // if (jfc.showSaveDialog((Component) PluginServices.getMainFrame())
-    // == JFileChooser.APPROVE_OPTION) {
-    //
-    // File file = jfc.getSelectedFile();
-    // String version = jfc.getDriverVersion();
-    // IFMapLegendDriver driver = jfc.getSuitableDriver();
-    //
-    // if(!(driver instanceof FMapGVLDriver)){
-    // Object[] options = {PluginServices.getText(this, "yes"),
-    // PluginServices.getText(this, "no")};
-    //
-    // int answer =
-    // JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
-    // PluginServices.getText(this, "not_GVSLEG_save_question")+"\n"+ //GVL
-    // changed to GVSLEG, be aware
-    // PluginServices.getText(this, "desea_continuar"),
-    // PluginServices.getText(this, "confirmation_dialog"),
-    // JOptionPane.YES_NO_OPTION,
-    // JOptionPane.QUESTION_MESSAGE,
-    // null,
-    // options, options[1]);
-    // if (answer!=JOptionPane.OK_OPTION) {
-    // // 'Cancel' pressed or window closed: don't save anythig, exit
-    // save dialog
-    // return;
-    // }
-    // }
-    //
-    // if (file.exists()) {
-    // Object[] options = {PluginServices.getText(this, "yes"),
-    // PluginServices.getText(this, "no"),
-    // PluginServices.getText(this, "Cancel")};
-    //
-    // int answer =
-    // JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
-    // PluginServices.getText(this,
-    // "fichero_ya_existe_seguro_desea_guardarlo"),
-    // PluginServices.getText(this, "confirmation_dialog"),
-    // JOptionPane.YES_NO_CANCEL_OPTION,
-    // JOptionPane.QUESTION_MESSAGE,
-    // null,
-    // options, options[1]);
-    // if (answer!=JOptionPane.OK_OPTION) {
-    // // 'Cancel' pressed or window closed: don't save anythig, exit
-    // save dialog
-    // return;
-    // }
-    // }
-    //
-    //
-    // try {
-    // driver.write(layer.getMapContext().getLayers(),layer,
-    // activePanel.getLegend(), file, version);
-    //
-    // } catch (LegendDriverException e1) {
-    // int type = e1.getType();
-    // String message=PluginServices.getText(this,
-    // "could_not_save_legend")+":\n";
-    //
-    // if ((type & LegendDriverException.SAVE_LEGEND_ERROR) != 0){
-    // type = type & ~LegendDriverException.SAVE_LEGEND_ERROR;
-    // message += PluginServices.getText(this,
-    // "error_writing_file")+".\n";
-    // }
-    // if ((type & LegendDriverException.UNSUPPORTED_LEGEND_CREATION) !=
-    // 0){
-    // type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_CREATION;
-    // message += "-"+ PluginServices.getText(this,
-    // "legend_format_not_yet_supported")+"\n";
-    // }
-    // if (type != 0) {
-    // message = "-"+PluginServices.getText(this, "unknown_error")+"\n";
-    // }
-    // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
-    // message);
-    // }
-    // }
-    // } else if (c.equals(getBtnLoadLegend())) {
-    //
-    // JLegendFileChooser jfc = new
-    // JLegendFileChooser(getLegendDrivers());
-    // jfc.setAcceptAllFileFilterUsed(false);
-    //
-    // if (jfc.showOpenDialog((Component) PluginServices.getMainFrame())
-    // == JFileChooser.APPROVE_OPTION) {
-    // File file=jfc.getSelectedFile();
-    // IFMapLegendDriver driver = jfc.getSuitableDriver();
-    // String path = file.getAbsolutePath();
-    // defaultLegendFolderPath = path.substring(0,
-    // path.lastIndexOf(File.separator));
-    //
-    // try {
-    // table = driver.read(layer.getMapContext().getLayers(),layer,
-    // file);
-    //
-    // if(table.containsKey(layer))
-    // applyLegend((ILegend) table.get(layer));
-    //
-    //
-    // } catch (LegendDriverException e1) {
-    // int type = e1.getType();
-    // String message = PluginServices.getText(this,
-    // "the_legend_will_not_be_applied")+":\n";
-    // boolean hasReason = false;
-    //
-    // if ((type &
-    // LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND) != 0){
-    // type = type &
-    // ~LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND;
-    // message +="-"+ PluginServices.getText(this,
-    // "classification_field_does_not_exists")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type & LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED)
-    // != 0){
-    // type = type &
-    // ~LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED;
-    // message += "-"+ PluginServices.getText(this,
-    // "legend_type_not_yet_supported")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type & LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED)
-    // != 0){
-    // type = type &
-    // ~LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED;
-    // message += "-"+ PluginServices.getText(this,
-    // "unsupported_symbol_type")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type & LegendDriverException.LAYER_SHAPETYPE_MISMATCH) !=
-    // 0){
-    // type = type & ~LegendDriverException.LAYER_SHAPETYPE_MISMATCH;
-    // message += "-"+ PluginServices.getText(this,
-    // "layer_geometry_and_legend_types_are_incompatible")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type & LegendDriverException.PARSE_LEGEND_FILE_ERROR) != 0){
-    // type = type & ~LegendDriverException.PARSE_LEGEND_FILE_ERROR;
-    // message += "-"+ PluginServices.getText(this,
-    // "failed_reading_file")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type &
-    // LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION) != 0){
-    // type = type &
-    // ~LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION;
-    // message += "-"+ PluginServices.getText(this,
-    // "unsupported_legend_file_version")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type & LegendDriverException.UNSUPPORTED_LEGEND_READING) !=
-    // 0){
-    // type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
-    // message +="-"+ PluginServices.getText(this,
-    // "unsupported_legend_file_format")+"\n";
-    // hasReason = true;
-    // }
-    // if ((type & LegendDriverException.LAYER_NAME_NOT_FOUND) != 0){
-    // type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
-    // message +="-"+ PluginServices.getText(this,
-    // "could_not_find_layer")+"\n";
-    // hasReason = true;
-    // }
-    // if (!hasReason) {
-    // message = "-"+ PluginServices.getText(this,
-    // "unknown_error")+"\n";
-    // }
-    // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
-    // message);
-    // }
-    // }
-    // }
-
-    // private IFMapLegendDriver[] getLegendDrivers() {
-    // Class<?>[] legendDriverClasses = legendDriverPool.toArray(new Class[0]);
-    // ArrayList<IFMapLegendDriver> drivers = new
-    // ArrayList<IFMapLegendDriver>();
-    // for (int i = 0; i < legendDriverClasses.length; i++) {
-    // String message = PluginServices.getText(this,
-    // "adding_legend_file_format_support")+": ";
-    // try {
-    // Class<?> c = legendDriverClasses[i];
-    // drivers.add((IFMapLegendDriver) c.newInstance());
-    // } catch (Exception e) {
-    // NotificationManager.addError(message+PluginServices.getText(this,
-    // "failed"), e);
-    // }
-    // NotificationManager.addInfo(message+PluginServices.getText(this, "OK"));
-    //
-    // }
-    // return (IFMapLegendDriver[]) drivers.toArray(new IFMapLegendDriver[0]);
-    // };
-
-    private String getExtension(File f) {
-        String ext = null;
-        String s = f.getName();
-        int i = s.lastIndexOf('.');
-
-        if (i > 0 && i < s.length() - 1) {
-            // ext = s.substring(i + 1).toLowerCase();
-            ext = s.substring(i).toLowerCase();
-        }
-        return ext;
-    }
-
     public LegendManager() {
         initialize();
     }
@@ -589,32 +206,28 @@
                 null, "",
                 javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                 javax.swing.border.TitledBorder.DEFAULT_POSITION, null, null));
-            topPanel.add(getBtnSaveLegend(), null);
-            topPanel.add(getBtnLoadLegend(), null);
+            topPanel.add(getBtnOptionalActions(), null);
         }
         return topPanel;
     }
 
-    private JButton getBtnSaveLegend() {
-        if (btnSaveLegend == null) {
-            btnSaveLegend =
-                new JButton(PluginServices.getText(this, "Guardar_leyenda")
+    private JButton getBtnOptionalActions() {
+        if (btnOptionalActions == null) {
+            btnOptionalActions =
+                new JButton(PluginServices.getText(this, "_Mas_opciones")
                     + "...");
-            btnSaveLegend.addActionListener(loadSaveLegendAction);
+            btnOptionalActions.addActionListener(new ActionListener() {
+                @Override
+                public void actionPerformed(ActionEvent e) {
+                    Point p = btnOptionalActions.getLocationOnScreen();
+                    menuOptionalActions.show(asJComponent(),0,0);
+                    menuOptionalActions.setLocation(p.x,p.y+btnOptionalActions.getHeight());
+                }
+            });
         }
-        return btnSaveLegend;
+        return btnOptionalActions;
     }
 
-    private JButton getBtnLoadLegend() {
-        if (btnLoadLegend == null) {
-            btnLoadLegend =
-                new JButton(PluginServices.getText(this, "Recuperar_leyenda")
-                    + "...");
-            btnLoadLegend.addActionListener(loadSaveLegendAction);
-        }
-        return btnLoadLegend;
-    }
-
     /**
      * This method initializes jTextArea
      *
@@ -687,8 +300,6 @@
      * bug, sorry. Just avoid this case or try to fix it (lol).<br>
      * </p>
      *
-     * @param page
-     *            , Class of type ILegendPanel
      * @deprecated use SymbologySwingManager.registerLegendEditor
      */
     public static void addLegendPage(Class<? extends ILegendPanel> iLegendPanelClass) {
@@ -707,12 +318,10 @@
             Iterator<ILegendPanel> it = manager.getLegendEditors(layer).iterator();
             while( it.hasNext() ) {
                 ILegendPanel page = it.next();
-                pages.put(page.getClass(), page);
+                pages.add(page);
             }
-
-            Enumeration<ILegendPanel> enume = pages.elements();
-            while (enume.hasMoreElements()) {
-                ILegendPanel page = enume.nextElement();
+            addOptionalActions();
+            for(ILegendPanel page : this.pages ) {
                 doInsertNode(treeModel, page);
             }
             getJTreeLegends().setModel(treeModel);
@@ -721,6 +330,33 @@
         }
     }
 
+    private void addOptionalActions() {
+        this.menuOptionalActions = new JPopupMenu();
+        Iterable<Action> actions = SymbologySwingLocator.getSwingManager().getOptionalActionOfLegendsPanel();
+        for( Action action : actions ) {
+            JMenuItemForOptionalAction item = new JMenuItemForOptionalAction(action);
+            this.menuOptionalActions.add(item);
+        }
+    }
+    
+    private class JMenuItemForOptionalAction extends JMenuItem implements ActionListener {
+
+        private static final long serialVersionUID = 1656264978338543368L;
+        Action action;
+        
+        JMenuItemForOptionalAction(Action action) {
+            this.action = action;
+            this.configurePropertiesFromAction(action);
+            this.addActionListener(this);
+        }
+        
+        @Override
+        public void actionPerformed(ActionEvent e) {
+            e.setSource(LegendManager.this);
+            this.action.actionPerformed(e);
+        }
+    }
+    
     @SuppressWarnings("unchecked")
     private DefaultMutableTreeNode findNode(Class searchID) {
         String title;
@@ -812,7 +448,8 @@
         Class parent_class = page.getParentClass();
 
         if (parent_class != null) {
-            if (pages.containsKey(parent_class)) {
+//            if (pages.containsKey(parent_class)) {
+            if (pages.contains(parent_class)) {
                 ILegendPanel parent = (ILegendPanel) pages.get(parent_class);
 
                 aux = doInsertNode(tm, parent);
@@ -880,7 +517,8 @@
         return jTreeLegends;
     }
 
-    private void setActivePage(ILegendPanel page) {
+    @Override
+    public void setActivePage(ILegendPanel page) {
         if (page.getPanel() == null) {
             // this is what happens when the user clicked in a parent node
             // which only acts as a folder, and does not manage any legend
@@ -904,6 +542,11 @@
         }
     }
 
+    @Override
+    public ILegendPanel getActivePage() {
+        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
+    }
+
     private void setIcon(ImageIcon icon) {
         getIconLabel().setIcon(icon);
     }
@@ -1079,9 +722,10 @@
     private void applyLegend(ILegend aLegend) {
         this.legend = aLegend;
         fillDialog();
-        Enumeration<Class<? extends ILegendPanel>> en = pages.keys();
-        while (en.hasMoreElements()) {
-            ILegendPanel page = (ILegendPanel) pages.get(en.nextElement());
+        for(ILegendPanel page : this.pages ) {
+//        Enumeration<Class<? extends ILegendPanel>> en = pages.keys();
+//        while (en.hasMoreElements()) {
+//            ILegendPanel page = (ILegendPanel) pages.get(en.nextElement());
             if (legend.getClass().equals(page.getLegendClass())) {
                 setActivePage(page);
                 expandAndSelect(page);
@@ -1098,10 +742,35 @@
     	return 800;
     }
 
-    // public static void addLegendDriver(Class<? extends IFMapLegendDriver>
-    // legendDriverClass) {
-    // if (!legendDriverPool.contains(legendDriverClass)) {
-    // legendDriverPool.add(legendDriverClass);
-    // }
-    // }
+    @Override
+    public ILegend getLegend() {
+        return this.legend;
+    }
+
+    @Override
+    public void setLegend(ILegend legend) {
+        applyLegend(legend);
+    }
+
+    @Override
+    public FLayer getLayer() {
+        return this.layer;
+    }
+
+    @Override
+    public void setLayer(FLayer layer) {
+        this.layer = layer;
+        applyLegend(((Classifiable) layer).getLegend());
+    }
+
+    @Override
+    public ILegendPanel getPage(Class<? extends ILegendPanel> pageClass) {
+        return this.pages.get(pageClass);
+    }
+
+    @Override
+    public Collection<ILegendPanel> getPages() {
+        return this.pages.asCollection();
+    }
+    
 }
