MOLE leadering style
arcgissamples\defensesolutions\TestLeaderStyle.java
/* Copyright 2010 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.defensesolutions;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

import java.io.File;
import java.util.ArrayList;

import com.esri.arcgis.beans.TOC.TOCBean;
import com.esri.arcgis.beans.map.MapBean;
import com.esri.arcgis.beans.toolbar.ToolbarBean;
import com.esri.arcgis.display.*;
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.ControlsMapZoomToLastExtentBackCommand;
import com.esri.arcgis.controls.ControlsMapZoomToLastExtentForwardCommand;
import com.esri.arcgis.controls.IMapControlEvents2Adapter;
import com.esri.arcgis.controls.IMapControlEvents2OnAfterDrawEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnAfterScreenDrawEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnBeforeScreenDrawEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnDoubleClickEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnExtentUpdatedEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnFullExtentUpdatedEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnKeyDownEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnKeyUpEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMapReplacedEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseDownEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseMoveEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseUpEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnOleDropEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnSelectionChangedEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnViewRefreshedEvent;
import com.esri.arcgis.geometry.*;


import com.esri.arcgis.defensesolutions.*;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.systemUI.esriCommandStyles;

/**
 * Description: Using the Map, TOC and Toolbar Control
 * Uses the MapBean to create and draw Force Elements and test a simple MOLE leadering style
 */
public class TestLeaderStyle extends JFrame  implements ActionListener {
  private static final long serialVersionUID = 1L;
  MapBean mapBean = null;
  TOCBean tocBean = null;
  ToolbarBean toolbarBean = null;
  JFrame frame = null;

    JButton leaderGraphicsButton;

    ArrayList<ICachedGraphic> collection = new ArrayList<ICachedGraphic>(); //Collection of Cached Graphics drawn

    IMoleCoreHelper moleCoreHelper = null;

    // Set the Default Path that works in windows with eclipse.
    // If not running from Eclipse (Linux/Solaris), the application
    // uses the AGSDEVKITJAVA environment variable to locate the data directory
    static String dataPath = ".." + File.separator + ".." +
      File.separator + "data" + File.separator;

    static String worldPath = dataPath + "world" + File.separator;
    static String baseMapShp = "dissolvecntry.shp";

  public TestLeaderStyle() {
    super("Java Sample:  TestLeaderStyle");

    try {
    mapBean = new MapBean();
    tocBean = new TOCBean();
    toolbarBean = new ToolbarBean();

    checkOrSetDataPath();

    mapBean.addShapeFile(worldPath, baseMapShp);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws java.io.IOException {
    EngineInitializer.initializeVisualBeans();

    AoInitialize aoInit = new AoInitialize();
        if (aoInit.isProductCodeAvailable( com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeEngine) == com.esri.arcgis.system.esriLicenseStatus.esriLicenseAvailable )
          aoInit.initialize( esriLicenseProductCode.esriLicenseProductCodeEngine);
        else {
          JOptionPane.showInputDialog( "Could not initialize an ArcGIS Engine license. Exiting application.");
            System.exit( -1);
        }

    TestLeaderStyle arFrame = new TestLeaderStyle();

    try {
      arFrame.display();
    } catch (java.io.IOException ioe) {
      ioe.printStackTrace();
    }
  }

    /**
     * Initializes the UI and then
     * Waits for the UI window closing event
     *
     * @throws java.io.IOException
     */
  public void display() throws java.io.IOException {

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    //set the control size
    mapBean.setSize(600,600);
    tocBean.setSize(200,600);
    toolbarBean.setSize(800, 25);
    getContentPane().add(mapBean, BorderLayout.CENTER);
    getContentPane().add(tocBean, BorderLayout.WEST);
    getContentPane().add(toolbarBean, BorderLayout.NORTH);

    toolbarBean.addItem(new ControlsMapZoomInTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconAndText); //ZoomIn
    toolbarBean.addItem(new ControlsMapZoomOutTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconAndText); //ZoomOut
    toolbarBean.addItem(new ControlsMapPanTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconAndText); //Pan
    toolbarBean.addItem(new ControlsMapFullExtentCommand(), 0, -1, true, 20, esriCommandStyles.esriCommandStyleTextOnly); //FullExtent
    toolbarBean.addItem(new ControlsMapZoomToLastExtentBackCommand(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleTextOnly); //ZoomToLastExtentBackCommand
    toolbarBean.addItem(new ControlsMapZoomToLastExtentForwardCommand(), 0, -1, false, 0,esriCommandStyles.esriCommandStyleTextOnly); //ZoomToLastExtentForwardCommand

    //  Set the TOC and toolbar buddy to the mapBean
    tocBean.setBuddyControl(mapBean);
    toolbarBean.setBuddyControl(mapBean);

      leaderGraphicsButton = new JButton("Leader Graphics");
      leaderGraphicsButton.setToolTipText("Leader Graphics");
      leaderGraphicsButton.addActionListener(this);
      JPanel panel = new JPanel();
      panel.add(leaderGraphicsButton);
      getContentPane().add(panel, BorderLayout.SOUTH);

    setSize(new Dimension(800,700));
    setVisible(true);

        mapBean.addIMapControlEvents2Listener(new MapControlListener());
  }

   /**
     * Checks for the required directory and prompts the user if it can't be found
     */
    public void checkOrSetDataPath()
    {
      // see if the required data files exist, check one of the files
    String checkFile = worldPath + baseMapShp;
    boolean exists = (new File(checkFile)).exists();
      if (!exists) {
        // we may not be running from IDE, see if AGSDEVKITJAVA defined and use it
      String arcgishome= null;
      try{
        arcgishome = System.getenv("AGSDEVKITJAVA");
      }catch(Error e){
        arcgishome = JOptionPane.showInputDialog("Please enter the path to the ArcGIS Engine directory");
      }
      dataPath = arcgishome+File.separator+"java"+File.separator+"samples"+File.separator+
        "data"+File.separator;

        worldPath = dataPath + "world" + File.separator;

      // check again if it exists
      checkFile = worldPath + baseMapShp;
      exists = (new File(checkFile)).exists();
        if (!exists) {
          // File or directory does not exist, that's bad, better warn the user
        // and let them try to correct
        JOptionPane.showMessageDialog(this, "Could not find required data directory\n" +
        "Warning: Application will not run as expected");
        }

      }
    }

   /**
   * Leader Graphics
   *
   * Applys a leadering style to two Force Element Graphics and then displays
   * the leadered graphics in the center of the map.
   */
  private void leaderGraphics() {
        try {
          IGraphicLeader pLeader = new GraphicLeader();
          IGraphicLeaderStyle pLeaderStyle = new HBarLdrStyle();
          // BracketLeaderStyle();
          pLeader.setStyleByRef(pLeaderStyle);

          //Configure leader's graphic properties
          ICachedGraphic cachedGraphicLeader = (ICachedGraphic)pLeader;
          cachedGraphicLeader.setSize(0.1); // 1 * mapBean.getActiveView().getExtent().getHeight());

          //Create and add Force Element Graphics to be leadered
          IPoint point1 = new Point();
          point1.putCoords(-79.0, 40.0);
          ICachedGraphic cachedGraphic1 = (ICachedGraphic)BuildFE(point1);
          cachedGraphic1.setSize(0.1);
          cachedGraphic1.refresh(mapBean.getActiveView().getScreenDisplay());
          pLeader.add((ILeaderable)cachedGraphic1);

          // and another
          IPoint point2 = new Point();
          point2.putCoords(-79.0, 39.5);
          ICachedGraphic cachedGraphic2 = (ICachedGraphic)BuildFE(point2);
          cachedGraphic2.setSize(0.1);
          cachedGraphic2.refresh(mapBean.getActiveView().getScreenDisplay());
          pLeader.add((ILeaderable)cachedGraphic2);

          // and another
          IPoint point3 = new Point();
          point3.putCoords(-79.0, 39.0);
          ICachedGraphic cachedGraphic3 = (ICachedGraphic)BuildFE(point3);
          cachedGraphic3.setSize(0.1);
          cachedGraphic3.refresh(mapBean.getActiveView().getScreenDisplay());
          pLeader.add((ILeaderable)cachedGraphic3);

          //Cached Graphics not stored in a displaylist must be drawn and manipulated manually.
          //Graphics stored in collection are redrawn in OnAfterDraw

          collection.add(cachedGraphicLeader);

          this.mapBean.getActiveView().refresh();
          // or alternately do partial refresh of only the leadered graphic area

          // Zoom to the area of the leadered graphics
          Envelope env = new Envelope();
          env.putCoords(-79.0, 41.0, -77.0, 37.0);

          this.mapBean.getActiveView().setExtent(env);

        }
        catch (Exception e) {
          e.printStackTrace();
        }
  }

    //  Handle actions
    public void actionPerformed(ActionEvent e) {

      if (e.getSource() == leaderGraphicsButton)
        {
         leaderGraphics();
        }
    }

    /**
     * Creates the renderer and displays a Progress Bar while initializing
     *
     * @return ICacheRenderer for creating 2525B graphics
     */
    ICacheRenderer get2525BRenderer() {

      ICacheRenderer renderer = null;

      try {
        if (moleCoreHelper == null)
          {
              // Show a Progress Bar to let the user know that this will take a few secs
              JProgressBar aJProgressBar = new JProgressBar();
              aJProgressBar.setIndeterminate(true);
              JFrame theFrame = new JFrame("Waiting on Renderer Initialization");
              theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Container contentPane = theFrame.getContentPane();
              contentPane.add(aJProgressBar, BorderLayout.NORTH);
              theFrame.setSize(500, 100);
              theFrame.setVisible(true);
              // end of Progress Bar creation code

              moleCoreHelper = new MoleCoreHelper();
              renderer = moleCoreHelper.getForceElementRenderer();

              // Hide the progress bar
                theFrame.setVisible(false);
          }
        else
        {
            renderer = moleCoreHelper.getForceElementRenderer();
        }

        }
        catch (Exception e) {
          e.printStackTrace();
        }
      return renderer;
    }
    /**
   * Utility function to create a force element located at the center of the
   * current map extent.
   *
   * @param IFEGraphicStyle
   * @return IFEGraphic
   */
  private IFEGraphic BuildFE(IPoint position) {

    IForceElement pForceElementObject;
    IForceElement2525BRenderer pForceElementRenderer;
    IFEGraphic pForceElementGraphic = null;

    try {
      pForceElementObject = new ForceElement();

      pForceElementObject.setMessageString("SFGPUCIA---K---");
      pForceElementObject.getPropertySet().setProperty("Name", "101st");
      pForceElementObject.getPropertySet().setProperty("Parent", "USA");

      pForceElementObject.setShapeByRef(position);

      //create force element graphic from force element object
      pForceElementRenderer = (IForceElement2525BRenderer)this.get2525BRenderer();
      pForceElementGraphic = (IFEGraphic)pForceElementRenderer.
                                                 graphicByForceElement(pForceElementObject);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return pForceElementGraphic;
  }

  /**
   * Class which extends map control event class IMapControlEvents2Adapter
   * @see com.esri.arcgis.beans.map.IMapControlEvents2Adapter
   */
  class MapControlListener extends IMapControlEvents2Adapter {
    private static final long serialVersionUID = 1L;

    /**
     * Event driven fired each time something is drawn on the map redraw items
     * stored in collection. Note start/finishDrawing is not called. This is
     * because the control framework handles this for the draw events.
     *
     * @param theEvent
     */
    public void onAfterDraw(IMapControlEvents2OnAfterDrawEvent theEvent) {
      try {

        IDisplay pDisplay = mapBean.getActiveView().getScreenDisplay();

        //Draw graphics not stored in a displaylist one at time
        int graphicCount = collection.size();
        if (graphicCount > 0)
            for (int i = 0; i < graphicCount; i++) {
            ICachedGraphic pGraphic = (ICachedGraphic) collection.get(i);
              pGraphic.draw(pDisplay, null);
            }
      }
      catch (Exception e) { e.printStackTrace(); }
    }

    public void onAfterScreenDraw(IMapControlEvents2OnAfterScreenDrawEvent
            theEvent) {}

    public void onBeforeScreenDraw(IMapControlEvents2OnBeforeScreenDrawEvent
             theEvent) {}

    public void onDoubleClick(IMapControlEvents2OnDoubleClickEvent theEvent) {}

    public void onExtentUpdated(IMapControlEvents2OnExtentUpdatedEvent theEvent) {}

    public void onFullExtentUpdated(IMapControlEvents2OnFullExtentUpdatedEvent
              theEvent) {}

    public void onKeyDown(IMapControlEvents2OnKeyDownEvent theEvent) {}

    public void onKeyUp(IMapControlEvents2OnKeyUpEvent theEvent) {}

    public void onMapReplaced(IMapControlEvents2OnMapReplacedEvent theEvent) {}

    public void onMouseDown(IMapControlEvents2OnMouseDownEvent theEvent) {}

    public void onMouseMove(final IMapControlEvents2OnMouseMoveEvent theEvent) {}

    public void onMouseUp(IMapControlEvents2OnMouseUpEvent theEvent) {}

    public void onOleDrop(IMapControlEvents2OnOleDropEvent theEvent) {}

    public void onSelectionChanged(IMapControlEvents2OnSelectionChangedEvent
                                     theEvent) {}

    public void onViewRefreshed(IMapControlEvents2OnViewRefreshedEvent theEvent) {}

  }
}