arcgissamples\symbologybean\AssignSymbolToGraphicElements.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
Assign symbol to graphic elements
arcgissamples\symbologybean\AssignSymbolToGraphicElements.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.symbologybean;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import com.esri.arcgis.beans.TOC.TOCBean;
import com.esri.arcgis.beans.pagelayout.PageLayoutBean;
import com.esri.arcgis.beans.symbology.SymbologyBean;
import com.esri.arcgis.beans.toolbar.ToolbarBean;
import com.esri.arcgis.carto.IElement;
import com.esri.arcgis.carto.ITextElement;
import com.esri.arcgis.carto.TextElement;
import com.esri.arcgis.carto.esriViewDrawPhase;
import com.esri.arcgis.controls.CommandsEnvironment;
import com.esri.arcgis.controls.ControlsNewFreeHandTool;
import com.esri.arcgis.controls.ControlsNewLineTool;
import com.esri.arcgis.controls.ControlsNewMarkerTool;
import com.esri.arcgis.controls.ControlsNewPolygonTool;
import com.esri.arcgis.controls.ControlsNewRectangleTool;
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.IPageLayoutControlEventsOnMouseDownEvent;
import com.esri.arcgis.controls.ISymbologyControlEventsAdapter;
import com.esri.arcgis.controls.ISymbologyControlEventsOnItemSelectedEvent;
import com.esri.arcgis.controls.ISymbologyStyleClass;
import com.esri.arcgis.controls.esriSymbologyStyleClass;
import com.esri.arcgis.display.IFillSymbol;
import com.esri.arcgis.display.IFillSymbolProxy;
import com.esri.arcgis.display.ILineSymbol;
import com.esri.arcgis.display.ILineSymbolProxy;
import com.esri.arcgis.display.IMarkerSymbolProxy;
import com.esri.arcgis.display.ITextSymbol;
import com.esri.arcgis.display.ITextSymbolProxy;
import com.esri.arcgis.display.ServerStyleGalleryItem;
import com.esri.arcgis.geometry.IPoint;
import com.esri.arcgis.geometry.Point;
import com.esri.arcgis.interop.AutomationException;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;
import com.esri.arcgis.systemUI.esriCommandStyles;

public class AssignSymbolToGraphicElements extends JFrame
{
  private static AoInitialize ao = null;

  private ToolbarBean toolbarBean = null;
  private SymbologyBean symbologyBean = null;
  private PageLayoutBean pageLayoutBean = null;
  private TOCBean tocBean = null;
  private ServerStyleGalleryItem styleGalleryItem = null;
  private CommandsEnvironment graphicProperties = null;
  JDialog progressDialog = null;
  JComboBox symbolComboBox = null;

  public AssignSymbolToGraphicElements()
  {
    try {
      buildAppFrame();
    } catch (Exception e2) {
      e2.printStackTrace();
    }
    addListener();
    setVisible(true);
    addWindowListener(new WindowAdapter()
    {
      public void windowClosed(WindowEvent e)
      {
        try
        {
          // Release license
          ao.shutdown();

          // Do not make any call to ArcObjects after ShutDownApplication()
          EngineInitializer.releaseAll();

          // Exit app
          System.exit(0);
        }
        catch (AutomationException e1)
        {
          e1.printStackTrace();
        }
        catch (IOException e1)
        {
          e1.printStackTrace();
        }
      }
    });
  }

  /**
   * main
   * @param args
   */
  public static void main(String[] args)
  {
    System.setProperty("AOJ_DISABLE_CASTING","");
    System.out.println("Starting AssignSymbolToGraphicElements - An ArcObjects Java SDK Developer Sample");
    EngineInitializer.initializeVisualBeans();
    initializeArcGISLicenses();
    AssignSymbolToGraphicElements app = new AssignSymbolToGraphicElements();
    try
    {
      //Get DEVKITHOME Home
      String devKitHome = System.getenv("AGSDEVKITJAVA");
      
      if (devKitHome == null)
      {
        JOptionPane.showMessageDialog(app, "ERROR - Developer Kit Home invalid. Exiting application...");
        System.exit(-1);
      }

      String fileName = devKitHome + "java" + File.separator + "samples" + File.separator
          + "data" + File.separator + "mxds" + File.separator + "brazil.mxd";

      File file = new File(fileName);
      if (!file.exists())
      {
        JOptionPane.showMessageDialog(app, "ERROR - Unable to find map document "
            + fileName
            + ".\nPlease use the Open file command to locate your map document.");
      }
      else
      {
        app.pageLayoutBean.loadMxFile(fileName, null);
      }
    }
    catch (java.lang.Throwable e)
    {
      e.printStackTrace();
    }
  }


  /**
   * Builds the application frame with Engine Controls and Swing Components
   */
  private void buildAppFrame() throws Exception
  {
    try
    {
      //Get DEVKITHOME Home
      String devKitHome = System.getenv("AGSDEVKITJAVA");
      
      if (devKitHome == null)
      {
        System.exit(-1);
      }

      String fileName = devKitHome + "java" + File.separator + "samples" + File.separator
          + "data" + File.separator + "mxds" + File.separator + "brazil.mxd";
    }
    catch (java.lang.Throwable e)
    {
      e.printStackTrace();
    }

    this.setSize(900, 600);
    this.setTitle("Assign Symbol to Graphic Elements");
    setContentPane(createAppContentPanel());
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    setVisible(true);
    setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
  }

  /**
   * Creates and returns the content panel
   */
  private JPanel createAppContentPanel() throws Exception
  {
    JPanel contentPanel = new JPanel();
    contentPanel.setLayout(new BorderLayout());
    contentPanel.add(createMainPanel(), BorderLayout.EAST);

    // add a pagelayout bean to content panel
    this.pageLayoutBean = new PageLayoutBean();
    contentPanel.add(this.pageLayoutBean, BorderLayout.CENTER);

    // add a toc bean to content panel
    this.tocBean = new TOCBean();
    tocBean.setBuddyControl(this.pageLayoutBean);
    contentPanel.add(this.tocBean, BorderLayout.WEST);

    // add a toolbar bean to content panel
    this.toolbarBean = createToolbarBean();
    contentPanel.add(this.toolbarBean, BorderLayout.NORTH);

    JPanel labelPanel = new JPanel();
    labelPanel.setLayout(new GridLayout(1, 1));
    JLabel label = new JLabel();
    label.setText("<html>1) Load a mapdocument into the pagelayout.<br>"  + 
        "2) Select a marker,line,fill or text symbol from the combobox and accordingly the different types of symbols will be shown in the right panel.<br>" +
        "3) Select new marker or line or polygon from toolbar and select symbols accordingly from the right panel and click on pagelayout to place these symbols.<br></html>");
    labelPanel.add(label);

    contentPanel.add(labelPanel, BorderLayout.SOUTH);

    return contentPanel;
  }

  /**
   * Creates a returns the main JPanel
   */
  private JPanel createMainPanel()
  {
    GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
    gridBagConstraints1.gridx = 0;
    gridBagConstraints1.anchor = GridBagConstraints.NORTH;
    gridBagConstraints1.fill = GridBagConstraints.BOTH;
    gridBagConstraints1.weighty = 1.0D;
    gridBagConstraints1.gridy = 1;
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = GridBagConstraints.NORTH;
    gridBagConstraints.weightx = 1.0;

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridBagLayout());
    this.symbolComboBox = createSymbolComboBox();
    mainPanel.add(this.symbolComboBox, gridBagConstraints);
    this.symbologyBean = createSymbologyBean();
    mainPanel.add(this.symbologyBean, gridBagConstraints1);

    return mainPanel;
  }

  /**
   * Creates a JComboBox to hold Style Classes
   */
  private JComboBox createSymbolComboBox()
  {
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);

    final JComboBox symbolComboBox = new JComboBox();
    symbolComboBox.setPreferredSize(new Dimension(100, 25));

    // Add style classes to the combo box
    symbolComboBox.addItem("Default Marker Symbol");
    symbolComboBox.addItem("Default Line Symbol");
    symbolComboBox.addItem("Default Fill Symbol");
    symbolComboBox.addItem("Default Text Symbol");
    symbolComboBox.setSelectedIndex(0);
    symbolComboBox.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent e)
      {
        try
        {
          if (symbolComboBox.getSelectedItem().toString().equalsIgnoreCase("Default Marker Symbol"))
          {
            symbologyBean.setStyleClass(esriSymbologyStyleClass.esriStyleClassMarkerSymbols);
          }
          else if (symbolComboBox.getSelectedItem().toString().equalsIgnoreCase("Default Line Symbol"))
          {
            symbologyBean.setStyleClass(esriSymbologyStyleClass.esriStyleClassLineSymbols);
          }
          else if (symbolComboBox.getSelectedItem().toString().equals("Default Fill Symbol"))
          {
            symbologyBean.setStyleClass(esriSymbologyStyleClass.esriStyleClassFillSymbols);
          }
          else if (symbolComboBox.getSelectedItem().toString().equals("Default Text Symbol"))
          {
            symbologyBean.setStyleClass(esriSymbologyStyleClass.esriStyleClassTextSymbols);
          }
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
        }
      }
    });

    return symbolComboBox;
  }

  /**
   * Creates and returns a SymbologyBean
   */
  private SymbologyBean createSymbologyBean()
  {
    SymbologyBean symbologyBean = null;
    try
    {
      symbologyBean = new SymbologyBean();
      symbologyBean.setPreferredSize(new Dimension(200, 50));
      
      //Get the ArcGIS Engine runtime, if it is available
      String runtimeHome = System.getenv("AGSENGINEJAVA");
          
      //If the ArcGIS Engine runtime is not available, then we can try ArcGIS Desktop runtime
      if(runtimeHome == null){
        runtimeHome = System.getenv("AGSDESKTOPJAVA");
      }
          
      //If no runtime is available, exit application gracefully
      if(runtimeHome == null){
        if(System.getProperty("os.name").toLowerCase().indexOf("win") > -1){
          System.err.println("You must have ArcGIS Engine Runtime or ArcGIS Desktop " + 
              "installed in order to execute this sample.");
          System.err.println("Install one of the products above, then re-run this sample.");
             System.err.println("Exiting execution of this sample...");
             System.exit(0);
        }else{
          System.err.println("You must have ArcGIS Engine Runtime installed " + 
              "in order to execute this sample.");
          System.err.println("Install the product above, then re-run this sample.");
          System.err.println("Exiting execution of this sample...");
          System.exit(0);  
        }
      }
          
      //Obtain relative path to the ESRI.ServerStyle file
      String esriStylePath = runtimeHome + "styles" + File.separator + "ESRI.ServerStyle";
        
      File styleFile = new File(esriStylePath);

          //Test to make sure style file is presente
      if(!styleFile.exists()){
        System.err.println("The ESRI.ServerStyle was not found in the following location: " + 
               styleFile.getParent());
        System.err.println("Verify that ESRI.ServerStyle can be located in the specified folder.");
        System.err.println("If not present, try uninstalling your ArcGIS software and reinstalling it.");
        System.err.println("Exiting execution of this sample...");
        System.exit(0);
      }
        
      //Load the ESRI.ServerStyle file into the SymbologyControl
      symbologyBean.loadStyleFile(esriStylePath);
      symbologyBean.setStyleClass(esriSymbologyStyleClass.esriStyleClassMarkerSymbols);
    }catch (AutomationException e){
      e.printStackTrace();
      return null;
    }catch (IOException e){
      e.printStackTrace();
      return null;
    }

    return symbologyBean;
  }

  /**
   * Create, initialize and return a toolbar bean
   */
  public ToolbarBean createToolbarBean() throws Exception
  {
    ToolbarBean toolbarBean = null;
    try
    {
      toolbarBean = new ToolbarBean();

      // Set the Buddy
      toolbarBean.setBuddyControl(this.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 ControlsSelectTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); // Select
      toolbarBean
          .addItem(new ControlsNewMarkerTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); // NewMarker
                                                            // Tool
      toolbarBean.addItem(new ControlsNewLineTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); // NewLine
                                                            // Tool
      toolbarBean.addItem(new ControlsNewFreeHandTool(), 0, -1, true, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // NewFreeHand Tool
      toolbarBean.addItem(new ControlsNewRectangleTool(), 0, -1, true, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // NewRectangle Tool
      toolbarBean.addItem(new ControlsNewPolygonTool(), 0, -1, true, 0,
          esriCommandStyles.esriCommandStyleIconOnly); // NewPolygon Tool
    }
    catch (Exception e)
    {
      System.out.println("Couldn't add commands or tools to toolbar bean.");
      e.printStackTrace();
    }

    return toolbarBean;
  }

  /**
   * Adds necessary listener to PageLayout and symbologycontrol to handle the PageLayoutReplaced and onItemSelected
   * events respectively
   */
  public void addListener()
  {
    try
    {
      // Get the CommandsEnvironment singleton
      graphicProperties = new CommandsEnvironment();

      // Create a new ServerStyleGalleryItem and set its name
      styleGalleryItem = new ServerStyleGalleryItem();
      
      // Set the commands environment marker symbol into the item
      styleGalleryItem.setItem(graphicProperties.getMarkerSymbol());

      // Get the marker symbol style class
      ISymbologyStyleClass styleClass = symbologyBean.getStyleClass2(esriSymbologyStyleClass.esriStyleClassMarkerSymbols);
      
      // Get the line symbol style class
      styleClass = symbologyBean.getStyleClass2(esriSymbologyStyleClass.esriStyleClassLineSymbols);
      
      // Set the commands environment line symbol into the item
      styleGalleryItem.setItem(graphicProperties.getLineSymbol());
      
      // Get the fill symbol style class
      styleClass = symbologyBean.getStyleClass2(esriSymbologyStyleClass.esriStyleClassFillSymbols);
      
      // Set the commands environment fill symbol into the item
      styleGalleryItem.setItem(graphicProperties.getFillSymbol());
      
      // Get the text symbol style class
      styleClass = symbologyBean.getStyleClass2(esriSymbologyStyleClass.esriStyleClassTextSymbols);
      
      // Set the commands environment text symbol into the item
      styleGalleryItem.setItem(graphicProperties.getTextSymbol());
      
      pageLayoutBean.getPageLayoutControl().addIPageLayoutControlEventsListener(new IPageLayoutControlEventsAdapter()
      {
        public void onMouseDown(final IPageLayoutControlEventsOnMouseDownEvent theEvent)
        {
          SwingUtilities.invokeLater(new Runnable()
          {
            public void run()
            {
              try
              {
                if (theEvent.getButton() != 2)
                  return;
                // Create a new point
                IPoint point = new Point();
                point.putCoords(theEvent.getPageX(), theEvent.getPageY());
                // Create a new text element
                ITextElement textElement = new TextElement();
                // Set the text to display todays date
                Date now = new Date();
                DateFormat df = DateFormat.getDateInstance();
                String dateTxt = df.format(now);
                textElement.setText(dateTxt);
                // Add element to graphics container using the CommandsEnvironment default text
                // symbol
                pageLayoutBean.addElement((IElement) textElement, point, 
                    graphicProperties.getTextSymbol(), "", 0);
                // Refresh the graphics
                pageLayoutBean.refresh(esriViewDrawPhase.esriViewGraphics, null, null);
              }
              catch (Exception e)
              {
                e.printStackTrace();
              }
            }
          });
        }
      });

      symbologyBean.addISymbologyControlEventsListener(new ISymbologyControlEventsAdapter()
      {
        public void onItemSelected(final ISymbologyControlEventsOnItemSelectedEvent theEvent)
        {
          SwingUtilities.invokeLater(new Runnable()
          {
            public void run()
            {
              try
              {
                styleGalleryItem = new ServerStyleGalleryItem(theEvent.getStyleGalleryItem());
                if (symbolComboBox.getSelectedItem().toString().equalsIgnoreCase("Default Marker Symbol")){
                  // Set the default marker symbol
                  graphicProperties.setMarkerSymbol(new IMarkerSymbolProxy(styleGalleryItem.getItem()));
                }else if (symbolComboBox.getSelectedItem().toString().equalsIgnoreCase("Default Line Symbol")){
                  // Set the default line symbol
                  graphicProperties.setLineSymbol(new ILineSymbolProxy(styleGalleryItem.getItem()));
                }else if (symbolComboBox.getSelectedItem().toString().equalsIgnoreCase("Default Fill Symbol")){
                  // Set the default fill symbol
                  graphicProperties.setFillSymbol(new IFillSymbolProxy(styleGalleryItem.getItem()));
                }else if (symbolComboBox.getSelectedItem().toString().equalsIgnoreCase("Default Text Symbol")){
                  // Set the default text symbol
                  graphicProperties.setTextSymbol(new ITextSymbolProxy(styleGalleryItem.getItem()));
                }
              }catch (Exception e){e.printStackTrace();}
            }
          });
        }
      });

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

  /**
   * Initializes the lowest available ArcGIS License
   */
  private static void initializeArcGISLicenses()
  {
    try{
      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);
      }else{
        System.err.println("Could not initialize an Engine or Basic License. Exiting application.");
        System.exit(-1);
      }
    }catch (Exception e){e.printStackTrace();}
  }

}