arcgissamples\mapbean\CADViewer.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
CAD viewer
arcgissamples\mapbean\CADViewer.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.
* 
*/
package arcgissamples.mapbean;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

import com.esri.arcgis.beans.map.MapBean;
import com.esri.arcgis.carto.CadLayer;
import com.esri.arcgis.controls.IMapControlEvents2Adapter;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseDownEvent;
import com.esri.arcgis.datasourcesfile.CadDrawingName;
import com.esri.arcgis.datasourcesfile.ICadDrawingDataset;
import com.esri.arcgis.datasourcesfile.ICadDrawingDatasetProxy;
import com.esri.arcgis.geodatabase.WorkspaceName;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;

/**
 * Description:This sample provides a stand alone java application containing a MapBean which can be used to to view CAD
 * data. When compiled the application can be asssociated with the most common CAD filename extensions (.DXF, DWG. and
 * .DNG) so that this will be the default application for opening files of these types. When opened, the application
 * allows the user to view the data including the abilities to zoom and pan.
 */

public class CadViewer extends JFrame implements ActionListener
{
  JPanel topPanel = null;
  JPanel mainPanel = null;
  JPanel bottomPanel = null;

  String helpString = "Use the left hand mouse button to zoom in and the Right mouse button to pan.";
  JLabel helpLabel = null;
  JButton zoomFullExtentButton = null;
  JButton loadCADDocumentButton = null;
  JTextField pathField = null;

  MapBean mapBean;
  String filePath;
  
  static AoInitialize aoInit;

  public CadViewer()
  {
    super("Cad Viewer");
    buildFrame();
    setSize(600, 400);
    setVisible(true);
    initControl();
  }

  /**
   * Initializes control
   */
  public void initControl()
  {
    try
    {
      mapBean.addIMapControlEvents2Listener(new MapControlListener());
    }
    catch (IOException ex)
    {
      System.out.println("Exception in initControl :" + ex);
      ex.printStackTrace();
    }

  }

  /**
   * This method builds 'this' frame as per the following diagram:
   * /----------------------------------------------------------\ | JButton | | JTextField | | |
   * |----------------------------------------------------------| | MapBean | | BorderLayout.CENTER | | | | | | | | |
   * |----------------------------------------------------------| | BorderLayout.SOUTH | | | | JButton JLabel | | |
   * \----------------------------------------------------------/
   */

  public void buildFrame()
  {
    topPanel = new JPanel();
    mainPanel = new JPanel();
    bottomPanel = new JPanel();

    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
    mainPanel.setLayout(new BorderLayout());
    bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    loadCADDocumentButton = new JButton("Load CAD Document");
    loadCADDocumentButton.addActionListener(this);

    pathField = new JTextField();
    pathField.setAlignmentX(0);
    pathField.setAlignmentY(0);
    topPanel.add(loadCADDocumentButton);
    topPanel.add(Box.createVerticalStrut(5));
    topPanel.add(pathField);
    topPanel.add(Box.createVerticalStrut(5));

    helpLabel = new JLabel(helpString);
    zoomFullExtentButton = new JButton("Zoom to Full Extent");
    zoomFullExtentButton.addActionListener(this);

    bottomPanel.add(zoomFullExtentButton);
    bottomPanel.add(helpLabel);

    // Create map control add it to the center of the main panel.
    mapBean = new MapBean();
    mainPanel.add(topPanel, BorderLayout.NORTH);
    mainPanel.add(mapBean, BorderLayout.CENTER);
    mainPanel.add(bottomPanel, BorderLayout.SOUTH);
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    getContentPane().add(mainPanel, BorderLayout.CENTER);

  }

  /**
   * @see java.awt.event.ActionListener#actionPerformed(ActionEvent event)
   * @param event
   */

  public void actionPerformed(ActionEvent event)
  {
    if (event.getSource() == loadCADDocumentButton)
    {
      try
      {
        if (loadFile())
        {
          addData();
        }
        else
          return;
      }
      catch (IOException ex)
      {
        System.out.println("Exception in loadCADDocumentButton#actionPerformed" + ex);
        ex.printStackTrace();
      }

    }

    if (event.getSource() == zoomFullExtentButton)
    {
      try
      {
        // Assign map controls extent property to the full extent of all the layers
        mapBean.setExtent(mapBean.getFullExtent());
      }
      catch (Exception ex)
      {
        System.out.println("Exception in zoomFullExtentButton action performed : " + ex);
        ex.printStackTrace();
      }
    }

  }

  /**
   * Method loadFile loads the specified CAD file (.DXF, .DWG or .DGN)
   */
  public boolean loadFile() throws IOException
  {
    // Open a JFileChooser for selecting CAD documents
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileFilter()
    {
      public boolean accept(File f)
      {
        return (f.isDirectory() || f.getAbsolutePath().toUpperCase().endsWith(".DXF")
            || f.getAbsolutePath().toUpperCase().endsWith(".DWG") || f.getAbsolutePath().toUpperCase()
            .endsWith(".DGN"));
      }

      public String getDescription()
      {
        return "Map Documents(*.DXF, .DWG or .DGN)";
      }
    });

    boolean loaded = false;
    int returnVal = 0;
    returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    {
      String fileChosen = chooser.getCurrentDirectory() + File.separator + chooser.getSelectedFile().getName();
      System.out.println("File picked: [" + fileChosen + "]");
      // set filepath the member variable.
      pathField.setText(fileChosen);
      filePath = fileChosen;
      loaded = true;

    }
    else
    {
      loaded = false;
    }
    return loaded;

  }

  /**
   * Adds data to control by using the file path.
   */

  public void addData()
  {
    // Get the last index of file separator
    try
    {
      int index = filePath.lastIndexOf(File.separator);
      // Get the directory path containing file path
      String strWorkspacePath = filePath.substring(0, index);
      String fileName = filePath.substring(index + 1);
      System.out.println(fileName);
      ICadDrawingDataset cadDrawingDataset = getCadDataSet(strWorkspacePath, fileName);
      if (cadDrawingDataset == null)
      {
        return;
      }
      // Create a cad layer using cad dataset and add it to map control.
      CadLayer cadLayer = new CadLayer();
      cadLayer.setCadDrawingDatasetByRef(cadDrawingDataset);
      cadLayer.setName(fileName);
      mapBean.addLayer(cadLayer, 0);
    }
    catch (IOException ex)
    {
      System.out.println("Exception in addData : " + ex);
      ex.printStackTrace();
    }
  }

  /**
   * Function which creates cad data set using cad workspace path and filname.
   */
  public ICadDrawingDataset getCadDataSet(String cadWorkspacePath, String cadFileName)
  {
    try
    {
      // Create a WorkspaceName object
      WorkspaceName workspaceName = new WorkspaceName();
      workspaceName.setPathName(cadWorkspacePath);
      workspaceName.setWorkspaceFactoryProgID("esriDataSourcesFile.CadWorkspaceFactory");

      // Create a CadDrawingName object
      CadDrawingName cadDrawingName = new CadDrawingName();
      cadDrawingName.setName(cadFileName);
      cadDrawingName.setWorkspaceNameByRef(workspaceName);

      // Open the CAD drawing
      ICadDrawingDataset cadDrawingDataset = new ICadDrawingDatasetProxy(cadDrawingName.open());

      return cadDrawingDataset;
    }
    catch (IOException ex)
    {
      System.out.println("Exception in getDataSet : " + ex);
      ex.printStackTrace();
      return null;
    }

  }

  /**
   * Description: Class which extends map control event class IMapControlEvents2Adapter
   * 
   * @see com.esri.arcgis.beans.map.IMapControlEvents2Adapter
   */

  class MapControlListener extends IMapControlEvents2Adapter
  {

    /**
     * @see com.esri.arcgis.beans.map.IMapControlEvents2Adapter#onMouseDown(IMapControlEvents2OnMouseDownEvent
     *      theEvent)
     * @param theEvent
     */

    public void onMouseDown(IMapControlEvents2OnMouseDownEvent theEvent)
    {
      try
      {
        // If left mouse button then zoom in
        if (theEvent.getButton() == 1)
        {
          mapBean.setExtent(mapBean.trackRectangle());
        }
        else if (theEvent.getButton() == 2)
        {
          mapBean.pan();
        }

      }
      catch (Exception ex)
      {
        System.out.println("Exception in MapControlListener#onMouseDown : " + ex);
        ex.printStackTrace();
      }

    }

  } // End of MapControlListener class

  /**
   * Main program to start the program execution.
   * 
   * @param s
   */

  public static void main(String s[])
  {
    try
    {
      EngineInitializer.initializeVisualBeans();
      // Set the system look and feel
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      
      aoInit = new AoInitialize();
      initializeArcGISLicenses(aoInit);
      
      CadViewer cadView = new CadViewer();
      cadView.setDefaultCloseOperation(CadViewer.EXIT_ON_CLOSE);
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
  }

  static void initializeArcGISLicenses(AoInitialize aoInit) {
    try {
      if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) 
          == esriLicenseStatus.esriLicenseAvailable)
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
      else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeBasic) 
          == esriLicenseStatus.esriLicenseAvailable)
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
      else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeStandard) 
          == esriLicenseStatus.esriLicenseAvailable)
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeStandard);
      else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeAdvanced) 
          == esriLicenseStatus.esriLicenseAvailable)
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
    } catch (Exception e) {e.printStackTrace();}
  }
}