MOLE feature layer renderer
arcgissamples\defensesolutions\MOLEFeatureLayerRenderer.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.io.*;
import java.awt.*;
import java.io.File;
import javax.swing.*;

import com.esri.arcgis.beans.TOC.*;
import com.esri.arcgis.beans.map.*;
import com.esri.arcgis.beans.toolbar.ToolbarBean;
import com.esri.arcgis.controls.*;
import com.esri.arcgis.systemUI.*;
import com.esri.arcgis.system.*;
import com.esri.arcgis.defensesolutions.*;
import com.esri.arcgis.carto.*;
import com.esri.arcgis.geodatabase.*;
import com.esri.arcgis.datasourcesGDB.*;
import com.esri.arcgis.interop.AutomationException;

/**
 * Title: FeatureLayerRenderer
 * Description: Demonstrates how to load MOLE layers
 *
 * See sample description in help system for more detailed information
 *
 */
public class MOLEFeatureLayerRenderer extends JFrame {
  private static final long serialVersionUID = 1L;
  MapBean mapBean;
    TOCBean tocControl;
  ToolbarBean toolbarBean;

    // 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 gdbPath = dataPath + "mole" + File.separator;

    static String baseMapShp = "dissolvecntry.shp";
    static String moleDataset = "mole_data.gdb";

    JPanel mainPanel;

    public MOLEFeatureLayerRenderer() {
        super("Data Renderer");
        try {

            Runnable r = new Runnable() {
                public void run() {
                    try {

                        initUI();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            };
            javax.swing.SwingUtilities.invokeAndWait(r);

            setSize(800, 600);
            try {

              checkOrSetDataPath();

                mapBean.addShapeFile(worldPath, baseMapShp);

              // 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

              LoadLayers();

              // Hide the progress bar
                theFrame.setVisible(false);

                // mapBean.setExtent(mapBean.getFullExtent());
                this.setVisible(true);

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


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

    }

    /**
     * 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;
        gdbPath = dataPath + "mole" + 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");
        }

      }
    }

    public void initUI(){
       //build the UI
       try{
           BorderLayout layout = new BorderLayout();

           layout.setHgap(3);
           layout.setVgap(3);
           mainPanel = new JPanel(layout);

           mapBean = new MapBean();
           tocControl = new TOCBean();
           toolbarBean = new ToolbarBean();

           tocControl.setPreferredSize(new Dimension(200, 600));

           mapBean.addIMapControlEvents2Listener(new mapListener());
           tocControl.setBuddyControl(mapBean);

           // Toolbar initialization
           toolbarBean.setBuddyControl(mapBean);

           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 ControlsMapZoomInFixedCommand(), 0, -1, false, 0,
                   esriCommandStyles.esriCommandStyleIconAndText);
           toolbarBean.addItem(new ControlsMapZoomOutFixedCommand(), 0, -1, false, 0,
                                  esriCommandStyles.esriCommandStyleIconAndText);
           toolbarBean.addItem(new ControlsMapPanTool(), 0, -1, true, //Pan
                                  0, esriCommandStyles.esriCommandStyleIconOnly);
           toolbarBean.addItem(new ControlsMapFullExtentCommand(), 0, -1, true,
                                  0, esriCommandStyles.esriCommandStyleIconOnly);// Full Extent
           // end of Toolbar initialization

           //prepare main panel
           mainPanel.add(toolbarBean, BorderLayout.NORTH);
           mainPanel.add(mapBean, BorderLayout.CENTER);
           mainPanel.add(tocControl, BorderLayout.WEST);
           mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

           getContentPane().add(mainPanel);
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

    public void LoadLayers(){
        try{

            mapBean.setMousePointer(esriControlsMousePointer.esriPointerHourglass);
            IWorkspaceFactory wsFactory = new FileGDBWorkspaceFactory();
            IWorkspace workspace;
            //Define data access
            workspace = wsFactory.openFromFile(gdbPath + File.separator + moleDataset, 0);
            IEnumDataset enumDataset;

            enumDataset = workspace.getDatasets(esriDatasetType.esriDTFeatureClass);

            enumDataset.reset();
            IDataset dataset = enumDataset.next();

            while (dataset != null){

              // Note: must use the proxy here casting to (IFeatureClass) does not seem to work
        IFeatureClass fc = new IFeatureClassProxy(dataset);

        String datasetName = dataset.getName();
        LoadLayer(fc, datasetName);

                dataset = enumDataset.next();
            }
            mapBean.setMousePointer(esriControlsMousePointer.esriPointerDefault);

        }catch(Exception e){
            e.printStackTrace();
            try{
                mapBean.setMousePointer(esriControlsMousePointer.
                                           esriPointerDefault);
            }catch(Exception ex){}
        }
    }

    public void LoadLayer(IFeatureClass featureClass, String name){
        try{

          // IMPORTANT: for simplicity this method assumes Tactical layers will contain
          // "Tactical in the dataset name
          if (name.toLowerCase().contains("tactical"))
          // or alternately one could key off the geometry type:
            // if (featureClass.getShapeType() == esriGeometryType.esriGeometryPolyline)
            {
                try {
                    TacticalGraphicLayer tgLayer = new TacticalGraphicLayer();
                    IFeatureLayer featureLayer = new FeatureLayer();

                    featureLayer.setName(name);
                    featureLayer.setFeatureClassByRef(featureClass);

                    tgLayer.setFeatureLayerByRef((IGeoFeatureLayer)
                            featureLayer);
                    tgLayer.setTextSize(0.1);
                    // Uncomment next line to set the size based on current extent
          // tgLayer.setTextSize(0.02 * mapBean.getActiveView().getExtent().getHeight());
                    ((ILayer)tgLayer).setName(name);
                    mapBean.addLayer((ILayer)tgLayer, 0);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else
            {
                try {
                    IForceElementLayer feLayer = new ForceElementLayer();

                    feLayer.setSize(0.05);
                    // Uncomment next line to set the size based on current extent
          // feLayer.setSize(0.02 * mapBean.getActiveView().getExtent().getHeight());

                    IFeatureLayer featureLayer = new FeatureLayer();
                    featureLayer.setName(name);
                    featureLayer.setFeatureClassByRef(featureClass);

                    ICachedGraphicFeatureLayer graphicFeatureLayer;
                    graphicFeatureLayer = (ICachedGraphicFeatureLayer)
                            feLayer;
                    graphicFeatureLayer.setFeatureLayerByRef(
                            (IGeoFeatureLayer)featureLayer);
                    ((ILayer)feLayer).setName(name);
                    mapBean.addLayer((ILayer)feLayer, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }

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

    //Use IMapControlEvents2Adapter class to handle only the events we need
    public class mapListener extends IMapControlEvents2Adapter{
    private static final long serialVersionUID = 1L;

    public void onDoubleClick(IMapControlEvents2OnDoubleClickEvent
                                  event) throws
                IOException, AutomationException {
            mapBean.setExtent(mapBean.getFullExtent());
        }

        public void onMouseDown(IMapControlEvents2OnMouseDownEvent
                                event) throws
                IOException, AutomationException {
            try {

              // TODO: add any test code you would like to perform on mouse down events

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

    public static void main(String[] args) {
        try {
            //Call initializer prior to using ArcGIS Java Beans
            EngineInitializer.initializeVisualBeans();

            //Initialize Engine license
            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);
            }

            new MOLEFeatureLayerRenderer();

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


    }
}