arcgissamples\scenario\map\MapComponent.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
Engine Viewer
arcgissamples\scenario\map\MapComponent.java
/* Copyright 2015 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 at <your ArcGIS install location>/DeveloperKit10.4/userestrictions.txt.
* 
*/
/*
 * ArcGIS Engine Developer Sample
 * Application Name: MapComponent.java
 */

package arcgissamples.scenario.map;

/**
 * Map component to display map image and to perform map operations such as
 * zoomin, zoomout , pan and identify.
 */
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;

import arcgissamples.scenario.MapActions;
import arcgissamples.scenario.toc.TocControl;

import com.esri.arcgis.carto.esriIdentifyOption;
import com.esri.arcgis.geometry.Envelope;

public class MapComponent extends JLayeredPane implements MapActions, ItemListener {
  private static final long serialVersionUID = 1L;
  MapInfo mapInfo = null;
  //Create ImageReader object for image display
  ImageReader reader;
  private BufferedImage _image;

  //display screen to hold the buffered image
  Display displayScreen;

  //Component to perform zoomin, zoomout..etc
  DrawTool drawTool;

  //Holds the list of maps
  JComboBox mapList = null;
  //Current focus Map
  private String activeMap = null;
  //Identify dialog object
  private static IdentifyDialog identifyDialog = null;
  //Toc control object
  TocControl tocControl;

  public MapComponent() {
    setLayout(null);
    init();
  }

  /** Initializes map control
   *
   */

  public void init() {
    displayScreen = new Display();
    //Get the instance of mapinfo
    mapInfo = MapInfo.getmapInfoInstance();
    //Get the reader object for generating image from mime data
    Iterator readers = ImageIO.getImageReadersByMIMEType("image/jpeg");
    reader = (ImageReader)readers.next();
    //Create a drawing tool for zoomin, zoomout ..etc.
    drawTool = new DrawTool(this);
    //Add mouse listener to draw tool perform rubberbanding
    addMouseListener(drawTool);
    //Add mouse motion listener for drag operation
    addMouseMotionListener(drawTool);
    //Add component draw tool on top of the component
    add(drawTool);
  }

  /**Sets the compobox control to hold the list of maps
   * @param cb JComboBox
   */

  public void setMapFrameComboBox(javax.swing.JComboBox comboBox) {
    mapList = comboBox;
    mapList.addItemListener(this);
  }

  public void itemStateChanged(java.awt.event.ItemEvent e) {
    if (e.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
      //set the focus map
      setActiveMap( (String) e.getItem());
    }
  }

  /** Sets the toc control
   *
   */
  public void setTocControl(TocControl tocControl) {
    this.tocControl = tocControl;
  }

  /**Adds the list of maps to combo box.
   */

  private void addMapNamesToDropDown() {
    //Get the map names
    java.util.Vector v = mapInfo.getMapNames();
    if(v == null) return;
    //Set the activemap variable
    activeMap = mapInfo.getActiveMap();
    //Get the data model of the combobox and remove all the data
    javax.swing.DefaultComboBoxModel model = ((javax.swing.DefaultComboBoxModel)this.mapList.getModel());
    mapList.removeItemListener(this);
    model.removeAllElements();
    //Add data
    for(int i =0 ; i < v.size(); i++) {
      String s = (String)v.get(i);
      model.addElement(s);
    }
    //Set the selected element to focus map
    mapList.setSelectedItem(activeMap);
    mapList.addItemListener(this);
    mapList.updateUI();
  }

  /** Sets the focus map
   * @param map String
   */

  public void setActiveMap(String map) {
    //Check for null object
    if(activeMap != null && map!= null
        && !activeMap.equalsIgnoreCase(map)) {
      activeMap = map;
      mapInfo.setActiveMap(map);
      //redraw the map image
      draw();
    }
  }

  /**
   * Get the active view
   * @return
   */

  public String getActiveMap() {
    return activeMap;
  }

  /**Get the map info object
   *
   * @return
   */

  public MapInfo getMapInfo() {
    return mapInfo;
  }

  /**stop the map server
   *
   */

  public void stopServer() {
    mapInfo.stop();
  }

  /**Sets the zoomin extent
   * If envelope is null then map is zoomed in by a fixed amount
   * @param e
   */

  public void setZoomInExtent(EnvelopeHelper envelope) {
    try {
      //If it was just a click
      if( envelope == null || envelope.getWidth() == 0 || envelope.getHeight() == 0) {
        Envelope currentEnvelope = (Envelope) mapInfo.getExtent();
        //zoom to 50%
        currentEnvelope.expand(0.5, 0.5, true);
        draw(currentEnvelope);
      } else {
        //transform the envelope to map coordinates and draw the map image
        draw((Envelope) mapInfo.transformScreenToMap(envelope));
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**Sets zoomout extent
   * If envelope is null then map is zoomed out by a fixed amount
   * @param e
   */

  public void setZoomOutExtent(EnvelopeHelper envelope) {
    try {
      //Get the current map extent
      Envelope currentEnvelope = (Envelope) mapInfo.getExtent();
      Envelope zoomEnvelope = null;
      //Check if it is a single click
      if( envelope == null || envelope.getWidth() == 0 || envelope.getHeight() == 0) {
        currentEnvelope.expand(2.0, 2.0, true);
        draw(currentEnvelope);
      }
      else {
        zoomEnvelope = (Envelope) mapInfo.transformScreenToMap(envelope);

        double pwidth, pheight, pxmin, pymin;
        double cwidth, cheight, cxmin, cymin;

        pwidth = zoomEnvelope.getWidth();
        pheight = zoomEnvelope.getHeight();
        pxmin = zoomEnvelope.getXMin();
        pymin = zoomEnvelope.getYMin();

        cwidth = currentEnvelope.getWidth();
        cheight = currentEnvelope.getHeight();
        cxmin = currentEnvelope.getXMin();
        cymin = currentEnvelope.getYMin();

        //Transform the current extent into the tracked extent
        // and expand the new active view
        double newwidth = cwidth * (cwidth / pwidth);
        double newheight = cheight * (cheight / pheight);
        double newxmin = cxmin - ( (pxmin - cxmin) * (cwidth / pwidth));
        double newymin = cymin - ( (pymin - cymin) * (cheight / pheight));

        zoomEnvelope.putCoords(newxmin, newymin, newxmin + newwidth,
            newymin + newheight);
        draw(zoomEnvelope);
      }
    }
    catch (Exception ex) {
    }
  }

  /** Pan with map's current extent
   */

  public void panWithCurrentExtent(int x , int y) {
    try {
      Envelope currentEnvelope = (Envelope) mapInfo.getExtent();
      Envelope newEnvelope = mapInfo.createNewEnvelope();
      //If it is a single click
      if(x == 0 && y == 0) {
        currentEnvelope.centerAt(mapInfo.transformScreenToMap(x, y));
        draw(currentEnvelope);
      }
      else {
        newEnvelope.setUpperLeft(mapInfo.transformScreenToMap(x, y));
        newEnvelope.setLowerRight(mapInfo.transformScreenToMap(x +
            this.getSize().width, y + this.getSize().height));
        draw(newEnvelope);
      }
    }
    catch (Exception ex) {}

  }

  /**Method to display identifydialog based on the click positions
   * @param envelop
   */

  public void identify(EnvelopeHelper envelope) {
    try {
      Envelope transformedEnvelope = (Envelope) mapInfo.transformScreenToMap(envelope);
      //Populate identify dialog with identify results
      if(identifyDialog != null) {
        //Get selected value from layer visibility drop down.
        String layerVisibilityData = identifyDialog.getDropDownValue();
        //Set the default value to topmost layer
        int identifyOption = esriIdentifyOption.esriIdentifyTopmost;
        //Set the identify option
        if(layerVisibilityData.equalsIgnoreCase(IdentifyDialog.VISIBLELAYER))
          identifyOption = esriIdentifyOption.esriIdentifyVisibleLayers;
        if(layerVisibilityData.equalsIgnoreCase(IdentifyDialog.ALLLAYERS))
          identifyOption = esriIdentifyOption.esriIdentifyAllLayers;
        //Get the identify results
        java.util.TreeMap tm = mapInfo.identify(transformedEnvelope, 1,
            identifyOption, null);
        //display identify dialog
        identifyDialog.popluateIdentifyResults(tm);
        identifyDialog.setVisible(true);
      }
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }

  }

  /** @see javax.swing.JComponent#doLayout
   * sets the size of the display screen and draw tool component
   * draws the map image when frame is resized
   */

  public void doLayout() {
    Dimension d = this.getSize();
    displayScreen.setSize(d.width, d.height);
    drawTool.setSize(d);
    if (_image != null) {
      draw();
    }
  }

  /**Draws the map with the current extent
   */

  public void draw() {
    draw(null);
  }

  /**Draws map with specified extent
   * @param env IEnvelope
   */

  public void draw(Envelope env) {
    try {
      mapInfo.setImageSize(getSize().width, getSize().height);
      if(env != null)
        mapInfo.setExtent(env);
      byte[] bytes = mapInfo.exportImage();
      ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
      ImageInputStream iis = ImageIO.createImageInputStream(byteArrayInputStream);
      reader.setInput(iis, true);
      _image = reader.read(0);
      displayScreen.getGraphics().drawRenderedImage(_image, new java.awt.geom.AffineTransform());
      repaint();
    }
    catch (Exception e) {
      e.printStackTrace();
      _image = null;
    }
  }

  /**@see javax.swing.JComponent#paintComponent
   * @param Graphcis g
   */

  public void paintComponent(Graphics g) {
    g.setColor(java.awt.Color.white);
    if (_image != null) {
      g.fillRect(0, 0, this.getSize().width, this.getSize().height);
      displayScreen.paint(g, 0, 0, this.getSize().width, this.getSize().width, true);
    }
    //There is no image yet so display a blank screen.
    else {
      g.fillRect(0, 0, this.getSize().width, this.getSize().height);
    }
  }

  /***Implementaion of Map Actions Inteface *****/

  /**
   * Opens a mxd file.
   * file chooser dialog is used to browse for mxd document
   */

  public void openMxd() {
    final String filePath = openFile();

    if (filePath == null)
      return;
    //perform in a seperate event thread to speed up the operation
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        Dimension d = getSize();
        //*Important* set the image size to that of screen size
        mapInfo.setImageSize(d.width, d.height);
        //Open mxd document
        mapInfo.opeMxdDocument(filePath);
        //Adds map names to map list combobox
        addMapNamesToDropDown();
        //draw the image
        draw();
        //set the focus map
        activeMap = mapInfo.getActiveMap();
      }
    });

    //Refresh the toc. Create a seperate event thread to speed up the operation
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        tocControl.refreshToc();
      }
    });
  }

  /**
   * Displays a file chooser dialog to browse for mxd documents
   */
  public String openFile() {
    FileDialog fileDialog = new FileDialog(new JFrame(), "Open MXD file", FileDialog.LOAD);
    fileDialog.setVisible(true);
    String path = fileDialog.getDirectory();
    String name = fileDialog.getFile();
    String fileChosen = path + "/" + name;
    return fileChosen;
  }

  /**
   * Sets the active tool to zoomin
   */
  public void zoomIn() {
    java.awt.Image cursorImage = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/arcgissamples/scenario/icons/zi_cur.gif"));
    Cursor zoominCursor = Toolkit.getDefaultToolkit().createCustomCursor(
        cursorImage, new java.awt.Point(6, 7), "ZoomIn");
    setCursor(zoominCursor);
    drawTool.setActiveTool(DrawTool.ZOOMIN);
  }

  /**
   * Sets the active tool to zoomOut
   */
  public void zoomOut() {
    java.awt.Image cursorImage = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/arcgissamples/scenario/icons/zo_cur.gif"));
    Cursor zoomOutCursor = Toolkit.getDefaultToolkit().createCustomCursor(
        cursorImage, new java.awt.Point(6, 7), "ZoomOut");
    setCursor(zoomOutCursor);
    drawTool.setActiveTool(DrawTool.ZOOMOUT);
  }

  /**
   * Sets the active tool to pan
   */
  public void pan() {
    java.awt.Image cursorImage = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/arcgissamples/scenario/icons/pan_cur.gif"));
    Cursor panCursor = Toolkit.getDefaultToolkit().createCustomCursor(
        cursorImage, new java.awt.Point(6, 7), "Pan");
    setCursor(panCursor);
    drawTool.setActiveTool(DrawTool.PAN);
  }

  /**
   * Sets the active tool to identify
   * Creates identify dialog
   */
  public void identify() {
    java.awt.Image cursorImage = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/arcgissamples/scenario/icons/id_cur.gif"));
    Cursor identifyCursor = Toolkit.getDefaultToolkit().createCustomCursor(
        cursorImage, new java.awt.Point(6, 7), "Identify");
    setCursor(identifyCursor);
    drawTool.setActiveTool(DrawTool.IDENTIFY);
    if (identifyDialog == null) {
      identifyDialog = new IdentifyDialog(null);
    }
    identifyDialog.setMapComponentByRef(this);
  }
}