Modify legend format
arcgissamples\symbologybean\ModifyLegendFormat.java
/* Copyright 2012 ESRI
* 
* All rights reserved under the copyright laws of the United States
* and applicable international laws, treaties, and conventions.
* 
* You may freely redistribute and use this sample code, with or
* without modification, provided you include the original copyright
* notice and use restrictions.
* 
* See the use restrictions.
* 
*/
package arcgissamples.symbologybean;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

import arcgissamples.symbologybean.ui.SymbologyFrame;

import com.esri.arcgis.beans.TOC.TOCBean;
import com.esri.arcgis.beans.pagelayout.PageLayoutBean;
import com.esri.arcgis.beans.toolbar.ToolbarBean;
import com.esri.arcgis.carto.IElement;
import com.esri.arcgis.carto.IGraphicsContainer;
import com.esri.arcgis.carto.IMapFrame;
import com.esri.arcgis.carto.IMapSurroundFrame;
import com.esri.arcgis.carto.esriViewDrawPhase;
import com.esri.arcgis.controls.ControlsMapFullExtentCommand;
import com.esri.arcgis.controls.ControlsMapPanTool;
import com.esri.arcgis.controls.ControlsMapZoomInTool;
import com.esri.arcgis.controls.ControlsMapZoomOutTool;
import com.esri.arcgis.controls.ControlsOpenDocCommand;
import com.esri.arcgis.controls.ControlsPageZoomInTool;
import com.esri.arcgis.controls.ControlsPageZoomOutTool;
import com.esri.arcgis.controls.ControlsPageZoomWholePageCommand;
import com.esri.arcgis.controls.ControlsSelectTool;
import com.esri.arcgis.controls.IPageLayoutControlEventsAdapter;
import com.esri.arcgis.controls.IPageLayoutControlEventsOnPageLayoutReplacedEvent;
import com.esri.arcgis.geometry.Envelope;
import com.esri.arcgis.geometry.IEnvelope;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.UID;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;
import com.esri.arcgis.systemUI.esriCommandStyles;

/**
 * This sample demonstrates using the SymbologyControl to change Area and Line Patches of Legend,
 */
public class ModifyLegendFormat extends JFrame implements ActionListener
{
  private static final long serialVersionUID = 1L;
  private JPanel jMainPanel;
  private JPanel jTopPanel;
  private JButton jBtnAddLegend;
  private JButton jBtnDeleteLegend;
  private JButton jBtnChangeAreaPatch;
  private JButton jBtnChangeLinePatch;
  private PageLayoutBean pageLayoutBean;
  private TOCBean tocBean;
  private ToolbarBean toolbarBean;
  private SymbologyFrame symbolForm;
  private IGraphicsContainer graphicsContainer;
  private IMapFrame mapFrame;
  private UID uID;
  private IMapSurroundFrame mapSurroundFrame;
  private IEnvelope envelope;
  private IElement element;

  /*
   * Main program to start the execution.
   */
  public static void main(String s[]) throws Exception
  {
    try
    {
      initVisualbeans();
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      initializeArcGISLicenses();
      new ModifyLegendFormat();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      System.out.println("Exiting ...");
    }
  }

  /*
   * Initialize engine in visualbeans mode
   */
  public static void initVisualbeans()
  {
    EngineInitializer.initializeVisualBeans();
  }

  /*
   * Check the availability and then initialize proper license
   */
  public static void initializeArcGISLicenses()
  {
    try
    {
      AoInitialize ao = new AoInitialize();
      if (ao.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) 
          == esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
      else if (ao.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeBasic) 
          == esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public ModifyLegendFormat() throws Exception
  {
    buildFrame();
    initControl();
    addListener();
    setSize(900, 600);
    setTitle("AreaLinePatches");
    setVisible(true);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    shutdownArcObjects();
  }

  /*
   * Build the frame with ArcGIS and Swing Components
   */
  public void buildFrame()
  {
    jMainPanel = new JPanel();
    jMainPanel.setLayout(new BorderLayout());
    pageLayoutBean = new PageLayoutBean();
    
    //Get DEVKITHOME Home
    String devKitHome = System.getenv("AGSDEVKITJAVA");
    
    if (devKitHome == null)
    {
      System.out.println("ArcObjects Java SDK is not installed on your system");
      System.out.println("Exiting ...");
      System.exit(0);
    }
    
    try
    {
      pageLayoutBean.loadMxFile(devKitHome + "java" + File.separator + "samples" + File.separator 
                         + "data" + File.separator + "mxds" + File.separator 
                         + "gulf of st. lawrence.mxd", 
                           null);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    tocBean = new TOCBean();
    toolbarBean = new ToolbarBean();
    tocBean.setSize(new Dimension(200, 100));
    toolbarBean.setSize(300, 25);

    jTopPanel = new JPanel();
    jTopPanel.add(toolbarBean);

    jTopPanel.setLayout(new GridLayout(1, 2));
    jTopPanel.add(getJButtonAddLegend(), null);
    jTopPanel.add(getJButtonDeleteLegend(), null);
    jTopPanel.add(getJButtonChangeAreaPatch(), null);
    jTopPanel.add(getJButtonChangeAreaPatch(), null);
    jTopPanel.add(getJButtonChangeLinePatch(), null);
    // jTopPanel.add(jButtonPanel);

    jMainPanel.add(tocBean, BorderLayout.WEST);
    jMainPanel.add(jTopPanel, BorderLayout.NORTH);
    jMainPanel.add(pageLayoutBean, BorderLayout.CENTER);
    jMainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    getContentPane().add(jMainPanel, BorderLayout.CENTER);
  }

  /*
   * Initialize button btnAddLegend
   */
  private JButton getJButtonAddLegend()
  {
    if (jBtnAddLegend == null)
    {
      try
      {
        jBtnAddLegend = new JButton();
        jBtnAddLegend.setText("AddLegend");
        jBtnAddLegend.setEnabled(true);
        jBtnAddLegend.addActionListener(this);
      }
      catch (java.lang.Throwable e)
      {
      }
    }
    return jBtnAddLegend;
  }

  /*
   * Initialize button btnDeleteLegend
   */
  private JButton getJButtonDeleteLegend()
  {
    if (jBtnDeleteLegend == null)
    {
      try
      {
        jBtnDeleteLegend = new JButton();
        jBtnDeleteLegend.setText("DeleteLegend");
        jBtnDeleteLegend.setEnabled(false);
        jBtnDeleteLegend.addActionListener(this);
      }
      catch (java.lang.Throwable e)
      {
      }
    }
    return jBtnDeleteLegend;
  }

  /*
   * Initialize button btnChangeAreaPatch
   */
  private JButton getJButtonChangeAreaPatch()
  {
    if (jBtnChangeAreaPatch == null)
    {
      try
      {
        jBtnChangeAreaPatch = new JButton();
        jBtnChangeAreaPatch.setText("ChangeAreaPatch");
        jBtnChangeAreaPatch.setEnabled(false);
        jBtnChangeAreaPatch.addActionListener(this);
      }
      catch (java.lang.Throwable e)
      {
      }
    }
    return jBtnChangeAreaPatch;
  }

  /*
   * Initialize button btnChangeLinePatch
   */
  private JButton getJButtonChangeLinePatch()
  {
    if (jBtnChangeLinePatch == null)
    {
      try
      {
        jBtnChangeLinePatch = new JButton();
        jBtnChangeLinePatch.setText("ChangeLinePatch");
        jBtnChangeLinePatch.setEnabled(false);
        jBtnChangeLinePatch.addActionListener(this);
      }
      catch (java.lang.Throwable e)
      {
      }
    }
    return jBtnChangeLinePatch;
  }

  /*
   * Initialize control and adds tools and commands to toolbar
   */
  public void initControl() throws Exception
  {
    try
    {
      // Set the Buddy
      toolbarBean.setBuddyControl(pageLayoutBean);
      tocBean.setBuddyControl(pageLayoutBean);
      // Add tool bar items..
      toolbarBean.addItem(new ControlsOpenDocCommand(), 0, 0, false, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // open
      toolbarBean.addItem(new ControlsPageZoomInTool(), 0, -1, true, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // PageZoomIn
      toolbarBean.addItem(new ControlsPageZoomOutTool(), 0, -1, false, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // PageZoomOut
      toolbarBean.addItem(new ControlsPageZoomWholePageCommand(), 0, -1, false, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // PagePan
      toolbarBean.addItem(new ControlsMapZoomInTool(), 0, -1, false, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // MapZoomIn
      toolbarBean.addItem(new ControlsMapZoomOutTool(), 0, -1, false, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // MapZoomout
      toolbarBean.addItem(new ControlsMapPanTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); // Map
                                                            // Pan
      toolbarBean.addItem(new ControlsMapFullExtentCommand(), 0, -1, false, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // MapFullExtent
      toolbarBean.addItem(new ControlsSelectTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); // Select
    }
    catch (Exception e)
    {
      System.out.println("Couldn't add commands or tools to toolbar bean.");
      e.printStackTrace();
    }
  }

  /*
   * Add necessary listener to Pagelayoutcontrol to handle PageLayoutReplaced event
   */
  @SuppressWarnings("serial")
  public void addListener()
  {
    try
    {
      pageLayoutBean.getPageLayoutControl().addIPageLayoutControlEventsListener(
          new IPageLayoutControlEventsAdapter()
          {
            public void onPageLayoutReplaced(IPageLayoutControlEventsOnPageLayoutReplacedEvent theEvent)
            {
              try
              {
                jBtnAddLegend.setEnabled(true);
                jBtnDeleteLegend.setEnabled(false);
                jBtnChangeAreaPatch.setEnabled(false);
                jBtnChangeLinePatch.setEnabled(false);
              }
              catch (Exception e)
              {
                e.printStackTrace();
              }
            }
          });
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  /*
   * This method is called when respective buttons are clicked
   */
  public void actionPerformed(ActionEvent e)
  {
    Runnable r = null;
    if (e.getSource() == jBtnAddLegend)
    {
      r = new Runnable()
      {
        public void run()
        {
          try
          {
            // Get the GraphicsContainer
            graphicsContainer = pageLayoutBean.getGraphicsContainer();
            // Get the MapFrame
            mapFrame = (IMapFrame) graphicsContainer
                .findFrame(pageLayoutBean.getActiveView().getFocusMap());
            if (mapFrame == null)
              return;
            // Create a legend
            uID = new UID();
            uID.setValue("esriCarto.Legend");
            // Create a MapSurroundFrame from the MapFrame
            mapSurroundFrame = mapFrame.createSurroundFrame(uID, null);
            if (mapSurroundFrame == null)
              return;
            if (mapSurroundFrame.getMapSurround() == null)
              return;
            // Set the name
            mapSurroundFrame.getMapSurround().setName("Legend");
            // Envelope for the legend
            envelope = new Envelope();
            envelope.putCoords(1, 1, 3.4, 2.4);
            // Set the geometry of the MapSurroundFrame
            element = (IElement) mapSurroundFrame;
            element.setGeometry(envelope);
            // Add the legend to the PageLayout
            pageLayoutBean.addElement(element, null, null, "Legend", 0);
            // Refresh the PageLayoutControl
            pageLayoutBean.getActiveView().partialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            // disable/enable buttons
            jBtnAddLegend.setEnabled(false);
            jBtnDeleteLegend.setEnabled(true);
            jBtnChangeAreaPatch.setEnabled(true);
            jBtnChangeLinePatch.setEnabled(true);
          }
          catch (Exception err)
          {
            err.printStackTrace();
          }
        }
      };
    }
    else if (e.getSource() == jBtnDeleteLegend)
    {
      r = new Runnable()
      {
        public void run()
        {
          try
          {
            // Find the legend
            element = pageLayoutBean.findElementByName("Legend", 1);
            if (element != null)
            {
              // Delete the legend
              graphicsContainer = pageLayoutBean.getGraphicsContainer();
              graphicsContainer.deleteElement(element);
              // Refresh the display
              pageLayoutBean.getActiveView().partialRefresh(esriViewDrawPhase.esriViewGraphics, null,
                  null);
              // enable/disable buttons
              jBtnAddLegend.setEnabled(true);
              jBtnDeleteLegend.setEnabled(false);
              jBtnChangeAreaPatch.setEnabled(false);
              jBtnChangeLinePatch.setEnabled(false);
            }
          }
          catch (Exception err)
          {
            err.printStackTrace();
          }
        }
      };
    }
    else if (e.getSource() == jBtnChangeAreaPatch)
    {
      r = new Runnable()
      {
        public void run()
        {
          symbolForm = new SymbologyFrame(pageLayoutBean, "areapatch");
          symbolForm.setVisible(true);
          symbolForm.setSize(487, 299);
        }
      };
    }
    else if (e.getSource() == jBtnChangeLinePatch)
    {
      r = new Runnable()
      {
        public void run()
        {
          symbolForm = new SymbologyFrame(pageLayoutBean, "linepatch");
          symbolForm.setVisible(true);
          symbolForm.setSize(487, 299);
        }
      };
    }
    Thread t = new Thread(r);
    t.start();
  }

  /*
   * Shutdown ArcObjects when the window closes
   */
  public void shutdownArcObjects() throws Exception
  {
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        try
        {
          new AoInitialize().shutdown();
          System.exit(0);
        }
        catch (Exception err)
        {
          err.printStackTrace();
          System.exit(1);
        }
      }
    });
  }

}