arcgissamples\cartography\FeatureClassDrawMain.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.cartography; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.UIManager; import com.esri.arcgis.beans.TOC.TOCBean; import com.esri.arcgis.beans.map.MapBean; import com.esri.arcgis.carto.FeatureLayer; import com.esri.arcgis.carto.IFeatureRenderer; import com.esri.arcgis.carto.UniqueValueRenderer; import com.esri.arcgis.carto.esriViewDrawPhase; import com.esri.arcgis.display.IEnumColors; import com.esri.arcgis.display.ISimpleFillSymbol; import com.esri.arcgis.display.ISymbol; import com.esri.arcgis.display.RandomColorRamp; import com.esri.arcgis.display.SimpleFillSymbol; import com.esri.arcgis.display.esriSimpleFillStyle; import com.esri.arcgis.geodatabase.IFeature; import com.esri.arcgis.geodatabase.IFeatureClass; import com.esri.arcgis.geodatabase.IFeatureCursor; import com.esri.arcgis.geodatabase.IField; import com.esri.arcgis.geodatabase.IFields; import com.esri.arcgis.geodatabase.esriFieldType; import com.esri.arcgis.geometry.esriGeometryType; 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; /** * This class provides a framework for demo application. * The sample demonstrates creating UniqueValueRenderer depend on featureClass and name of attribute field. */ public class FeatureClassDrawMain extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; static AoInitialize aoint; TOCBean tocBean = new TOCBean(); MapBean mapBean = new MapBean(); TextField textFieldName = new TextField(); Button buttonOpenFile = new Button(); Button buttonFeatureRenderer = new Button(); public static void main(String s[]) { System.out.println("Starting \"Feature Class Draw\" - An ArcObjects Java SDK Developer Sample"); //Get DEVKITHOME Home String devKitHome = System.getenv("AGSDEVKITJAVA"); if (!(new File(devKitHome).exists())) { System.out.println(devKitHome + " does not exist.\nExiting..."); System.exit(-1); } // // Change the following lines if you want to start with different data // String workspacePath = devKitHome + "java" + File.separator + "samples" + File.separator + "data" + File.separator + "usa"; String featureClassName = "states"; File shapefileFile = new File(workspacePath, featureClassName + ".shp"); if (!shapefileFile.exists()) { System.out.println("Shapefile does not exist: " + shapefileFile.getAbsolutePath()); System.exit(0); } try { EngineInitializer.initializeVisualBeans(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); initializeArcGISLicenses(); FeatureClassDrawMain thisApp = new FeatureClassDrawMain(); thisApp.initUI(workspacePath, featureClassName); } catch (Exception ex) { System.out.println("Sample failed: " + ex.getMessage()); ex.printStackTrace(); } } static void initializeArcGISLicenses() { try { AoInitialize ao = new AoInitialize(); if (ao.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) == esriLicenseStatus.esriLicenseAvailable) ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine); else if (ao.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeArcView) == esriLicenseStatus.esriLicenseAvailable) ao.initialize(esriLicenseProductCode.esriLicenseProductCodeArcView); } catch (Exception e) { e.printStackTrace(); } } /* * Lay out the User Interface, and set up event listeners */ private void initUI(String path, String name) throws AutomationException, IOException { this.setTitle("Feature Class Draw Sample Application"); this.setSize(new Dimension(600, 500)); this.getContentPane().setLayout(new BorderLayout()); Panel loadPanel = new Panel(new FlowLayout(FlowLayout.LEADING)); Label labelComment = new Label(); labelComment.setText("Open a polygonal feature shapefile, such as states.shp."); this.buttonOpenFile.setLabel("Open File..."); loadPanel.add(labelComment); loadPanel.add(this.buttonOpenFile); Panel rendererPanel = new Panel(new FlowLayout(FlowLayout.LEADING)); Label label = new Label(); label.setText("Use text field names such as STATE_NAME and STATE_ABBR ..."); this.textFieldName.setText("STATE_NAME"); this.buttonFeatureRenderer.setLabel("Render"); rendererPanel.add(label); rendererPanel.add(this.textFieldName); rendererPanel.add(this.buttonFeatureRenderer); Panel toolPanel = new Panel(new GridLayout(2,1)); toolPanel.add(loadPanel); toolPanel.add(rendererPanel); Panel nestPanel = new Panel(); nestPanel.add(toolPanel); this.getContentPane().add(this.mapBean, BorderLayout.CENTER); this.getContentPane().add(this.tocBean, BorderLayout.WEST); this.getContentPane().add(nestPanel, BorderLayout.SOUTH); this.mapBean.clearLayers(); this.mapBean.addShapeFile(path, name); this.tocBean.setBuddyControl(this.mapBean); // update map this.setVisible(true); this.mapBean.refresh(esriViewDrawPhase.esriViewGeography, null, null); // set listeners this.buttonOpenFile.addActionListener(this); this.buttonFeatureRenderer.addActionListener(this); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { try { new AoInitialize().shutdown(); } catch(IOException ex) { // exit anyway } System.out.println("Done."); System.exit(0); } }); } /** * implements interface ActionListener * @see ActionListener#actionPerformed */ public void actionPerformed(ActionEvent event) { Object eventSource = event.getSource(); // Open File if (eventSource == this.buttonOpenFile) { try { FileDialog fileDialog = new FileDialog(this, "Open File", FileDialog.LOAD); fileDialog.setVisible(true); String path = fileDialog.getDirectory(); String name = fileDialog.getFile(); this.mapBean.clearLayers(); this.mapBean.addShapeFile(path, name); this.tocBean.setBuddyControl(this.mapBean); } catch (java.lang.Exception ex) { System.out.println("Can't open file, exception:" + ex); } } if (eventSource == this.buttonFeatureRenderer) { try { FeatureLayer featureLayer = (FeatureLayer)this.mapBean.getLayer(0); IFeatureClass featureClass = featureLayer.getFeatureClass(); // only support polygon features if (featureClass.getShapeType() != esriGeometryType.esriGeometryPolygon) { System.out.println("The shapefile's feature class is not of type Polygon. Try another."); return; } IFeatureRenderer featureRenderer = createRenderer(featureClass, this.textFieldName.getText()); if (featureRenderer == null) { // System.out.println("Couldn't create renderer. Try again."); return; } featureLayer.setRendererByRef(featureRenderer); this.tocBean.update(); this.mapBean.refresh(esriViewDrawPhase.esriViewGeography, null, null); } catch (java.lang.Exception ex) { ex.printStackTrace(); // never happened } } } /** * Create UniqueValueRenderer based on featureclass and name of field. */ private UniqueValueRenderer createRenderer(IFeatureClass featureClass, String fieldName) throws IOException, AutomationException { // Make the renderer and the classification objects UniqueValueRenderer renderer = new UniqueValueRenderer(); renderer.setFieldCount(1); renderer.setField(0, fieldName); SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(); simpleFillSymbol.setStyle(esriSimpleFillStyle.esriSFSSolid); simpleFillSymbol.getOutline().setWidth(0.4); renderer.setDefaultSymbol(simpleFillSymbol); renderer.setUseDefaultSymbol(true); // The chosen field must exist for this feature class to continue IFields fields = featureClass.getFields(); int fieldIndex = fields.findField(fieldName); if (fieldIndex == -1) { System.out.print("Try one of these fields: "); int nFields = fields.getFieldCount(); for (int ctr = 0; ctr < nFields; ctr++) { IField field = fields.getField(ctr); if (field.getType() == esriFieldType.esriFieldTypeString) { System.out.print(field.getName() + " "); } } System.out.println(); return null; } //ArrayList list = new ArrayList(); ArrayList<String> list = new ArrayList<String>(); IFeatureCursor featureCursor = featureClass.search(null, false); for (IFeature feature = featureCursor.nextFeature(); feature != null; feature = featureCursor.nextFeature()) { String fieldValueString = (String) feature.getValue(fieldIndex); // Test to see if we've already added this value // to the renderer, if not, then add it. if (list.contains(fieldValueString)) { continue; } list.add(fieldValueString); SimpleFillSymbol symbol = new SimpleFillSymbol(); symbol.setStyle(esriSimpleFillStyle.esriSFSSolid); symbol.getOutline().setWidth(0.4); renderer.addValue(fieldValueString, "Name", symbol); renderer.setLabel(fieldValueString, fieldValueString); renderer.setSymbol(fieldValueString, symbol); } // now that we know how many unique values there are, // we can size the color ramp and assign the colors. RandomColorRamp randomColorRamp = new RandomColorRamp(); randomColorRamp.setMinSaturation(25); randomColorRamp.setMaxSaturation(75); randomColorRamp.setMinValue(50); randomColorRamp.setMaxValue(100); randomColorRamp.setStartHue(0); randomColorRamp.setEndHue(360); randomColorRamp.setUseSeed(true); randomColorRamp.setSeed((int) System.currentTimeMillis()); randomColorRamp.setSize(renderer.getValueCount()); boolean result[] = new boolean[1]; randomColorRamp.createRamp(result); IEnumColors enumColors = randomColorRamp.getColors(); enumColors.reset(); int valueCount = renderer.getValueCount(); for (int valueCtr = 0; valueCtr < valueCount; valueCtr++) { String value = renderer.getValue(valueCtr); ISymbol symbol = renderer.getSymbol(value); ISimpleFillSymbol iSimpleFillSymbol = (ISimpleFillSymbol) symbol; iSimpleFillSymbol.setColor(enumColors.next()); renderer.setSymbol(value, symbol); } // If you didn't use a color ramp that was predefined // in a style, you need to use "Custom" here, otherwise // use the name of the color ramp you chose. renderer.setColorScheme("Somewhat Random"); renderer.setFieldType(0, true); return renderer; } }