arcgissamples\mapbean\BufferFeatures.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.mapbean; import java.io.File; import java.awt.Dimension; import java.awt.Frame; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.UIManager; import com.esri.arcgis.beans.TOC.TOCBean; import com.esri.arcgis.beans.map.MapBean; import com.esri.arcgis.beans.toolbar.ToolbarBean; import com.esri.arcgis.carto.IActiveView; import com.esri.arcgis.carto.IMap; import com.esri.arcgis.carto.ISelection; import com.esri.arcgis.carto.MapSelection; import com.esri.arcgis.controls.ControlsMapFullExtentCommand; import com.esri.arcgis.controls.ControlsMapPanTool; import com.esri.arcgis.controls.ControlsMapZoomInFixedCommand; import com.esri.arcgis.controls.ControlsMapZoomInTool; import com.esri.arcgis.controls.ControlsMapZoomOutFixedCommand; import com.esri.arcgis.controls.ControlsMapZoomOutTool; import com.esri.arcgis.controls.ControlsMapZoomPanTool; import com.esri.arcgis.controls.ControlsMapZoomToLastExtentBackCommand; import com.esri.arcgis.controls.ControlsMapZoomToLastExtentForwardCommand; import com.esri.arcgis.controls.ControlsOpenDocCommand; import com.esri.arcgis.controls.ControlsSelectFeaturesTool; import com.esri.arcgis.controls.ControlsSelectTool; import com.esri.arcgis.datasourcesfile.ShapefileWorkspaceFactory; import com.esri.arcgis.display.IScreenDisplay; import com.esri.arcgis.display.RgbColor; import com.esri.arcgis.display.SimpleFillSymbol; import com.esri.arcgis.display.esriSimpleFillStyle; import com.esri.arcgis.geodatabase.Field; import com.esri.arcgis.geodatabase.Fields; import com.esri.arcgis.geodatabase.GeometryDef; import com.esri.arcgis.geodatabase.IFeature; import com.esri.arcgis.geodatabase.IFeatureBuffer; import com.esri.arcgis.geodatabase.IFeatureClass; import com.esri.arcgis.geodatabase.IFeatureCursor; import com.esri.arcgis.geodatabase.IQueryFilter; import com.esri.arcgis.geodatabase.QueryFilter; import com.esri.arcgis.geodatabase.Workspace; import com.esri.arcgis.geodatabase.esriFeatureType; import com.esri.arcgis.geodatabase.esriFieldType; import com.esri.arcgis.geometry.IGeometry; import com.esri.arcgis.geometry.Point; import com.esri.arcgis.geometry.Polygon; import com.esri.arcgis.geometry.Polyline; import com.esri.arcgis.geometry.UnknownCoordinateSystem; import com.esri.arcgis.geometry.esriGeometryType; 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; /** * This sample demonstrates how to buffer selected features in a layer, and how to display the resulting buffer polygon * on a Map. The buffer distance is hard-coded to "1.0", which assumes that the shapefile data for the layer is stored * in decimal degrees, for simplicity. */ public class BufferFeatures extends JFrame { MapBean mapBean = new MapBean(); ToolbarBean toolbarBean = new ToolbarBean(); // Control TOCBean toc = new TOCBean(); JPanel toolBarPanel = new JPanel(); JButton btnBuffer = new JButton("Buffer selected features"); IGeometry result = null; String _distance = null; static AoInitialize aoInit; public BufferFeatures() { this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent wevt) { try { aoInit.shutdown(); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Done."); System.exit(0); } } }); buildFrame(); } private void buildFrame() { getContentPane().setLayout(new java.awt.BorderLayout()); getContentPane().add(mapBean, java.awt.BorderLayout.CENTER); getContentPane().add(toolBarPanel, java.awt.BorderLayout.NORTH); getContentPane().add(toc, java.awt.BorderLayout.WEST); BoxLayout boxLayout = new BoxLayout(toolBarPanel, BoxLayout.X_AXIS); toolBarPanel.setLayout(boxLayout); toc.setSize(150, 580); toolBarPanel.add(toolbarBean); toolBarPanel.add(btnBuffer); btnBuffer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { processBufferButtonAction(evt); } }); } /** * Processes buffer when buffer button clicked. */ public void processBufferButtonAction(ActionEvent evt) { // Buffer the selected Features... BufferUI ui = new BufferUI(this, "Buffer Properties", true); ui.setSize(300, 250); ui.setResizable(false); ui.setVisible(true); } public void doBuffer(String distance) { _distance = distance; try { IScreenDisplay screenDisplay = mapBean.getActiveView().getScreenDisplay(); SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(); RgbColor color = new RgbColor(); color.setRed(255); color.setGreen(0); color.setBlue(0); simpleFillSymbol.setColor(color); simpleFillSymbol.setStyle(esriSimpleFillStyle.esriSFSDiagonalCross); IQueryFilter qfilter = new QueryFilter(); qfilter.setWhereClause(" "); IActiveView activeView = mapBean.getActiveView(); IMap focusMap = activeView.getFocusMap(); ISelection featureSelection = focusMap.getFeatureSelection(); MapSelection features = new MapSelection(featureSelection); IFeature feature = features.next(); while (feature != null) { IGeometry iGeometry = feature.getShape(); IGeometry buffer = null; Polygon polygon = null; Polyline polyline = null; Point point = null; if (iGeometry instanceof Polygon) { polygon = (Polygon) feature.getShape(); buffer = polygon.buffer(Double.parseDouble(distance)); result = polygon.union(buffer); } else if (iGeometry instanceof Polyline) { polyline = (Polyline) feature.getShape(); buffer = polyline.buffer(Double.parseDouble(distance)); result = buffer; } else { // must be a Point point = (Point) feature.getShape(); buffer = point.buffer(Double.parseDouble(distance)); result = buffer; } if (result == null) { JOptionPane.showMessageDialog(this, "Please select features first."); continue; } screenDisplay.startDrawing(0, Short.parseShort("0")); screenDisplay.setSymbol(simpleFillSymbol); screenDisplay.drawPolygon(result); screenDisplay.finishDrawing(); feature = features.next(); } } catch (Exception ex) { ex.printStackTrace(); } } /** * Saves shape file */ public void doSaveBuffer(String output) { java.io.File outputFile = new java.io.File(output); if (outputFile.isDirectory()) { JOptionPane.showMessageDialog(this, "The specified file is actually a directory. Please enter a shapefile name."); return; } String strFClassName = outputFile.getName(); if (this.result != null) { try { ShapefileWorkspaceFactory factory = new ShapefileWorkspaceFactory(); Workspace workspace = (Workspace) factory.openFromFile(outputFile.getParent(), 0); // Make sure the featureclass doesn't already exist... try { IFeatureClass test = workspace.openFeatureClass(strFClassName + ".shp"); if (test != null) { JOptionPane.showMessageDialog(this, strFClassName + " already exists. Please specify a unique shapefile name"); return; } } catch (Exception e) {/* It's okay if the file doesn't exist */ } // Set up the Fields... // Make the shape field it will need a geometry definition, with a spatial reference Fields fields = new Fields(); Field field = new Field(); field.setName("Shape"); field.setType(esriFieldType.esriFieldTypeGeometry); GeometryDef geometryDef = new GeometryDef(); geometryDef.setGeometryType(esriGeometryType.esriGeometryPolygon); geometryDef.setSpatialReferenceByRef(new UnknownCoordinateSystem()); field.setGeometryDefByRef(geometryDef); fields.addField(field); // Add another miscellaneous text field field = new Field(); field.setLength(30); field.setName("Scale"); field.setType(esriFieldType.esriFieldTypeDouble); fields.addField(field); // Create the shapefile (some parameters apply to geodatabase options and can be defaulted as Nothing) IFeatureClass featureClass = workspace.createFeatureClass(strFClassName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); // Now, add the buffer polygon as a feature IFeatureCursor featureCursor = featureClass.IFeatureClass_insert(true); IFeatureBuffer featureBuffer = featureClass.createFeatureBuffer(); featureBuffer.setShapeByRef(result); int index = featureBuffer.getFields().findField("Scale"); featureBuffer.setValue(index, new Double(Double.parseDouble(_distance))); featureCursor.insertFeature(featureBuffer); featureCursor.flush(); } catch (Exception e) { System.out.println("Error saving shapefile: " + e); } } } /** * Initializes all the controls */ public void display() { try { toolbarBean.setBuddyControl(mapBean); toc.setBuddyControl(mapBean); toolbarBean.addItem(new ControlsOpenDocCommand(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsSelectFeaturesTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean .addItem(new ControlsMapZoomInTool(), 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapZoomOutTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapPanTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapZoomInFixedCommand(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapZoomOutFixedCommand(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapZoomPanTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapFullExtentCommand(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapZoomToLastExtentBackCommand(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsMapZoomToLastExtentForwardCommand(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); toolbarBean.addItem(new ControlsSelectTool(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { try{ EngineInitializer.initializeVisualBeans(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); aoInit = new AoInitialize(); initializeArcGISLicenses(aoInit); BufferFeatures bufferFeatures = new BufferFeatures(); bufferFeatures.setSize(780, 500); bufferFeatures.setTitle("BufferFeatures - ArcObjects Java SDK Developer Sample"); bufferFeatures.setVisible(true); bufferFeatures.display(); bufferFeatures.setDefaultCloseOperation(JFrame.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.esriLicenseProductCodeArcView) == esriLicenseStatus.esriLicenseAvailable) aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeArcView); else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeArcEditor) == esriLicenseStatus.esriLicenseAvailable) aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeArcEditor); else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeArcInfo) == esriLicenseStatus.esriLicenseAvailable) aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo); } catch (Exception e) {e.printStackTrace();} } /** * Dialog to display buffer attributes. */ class BufferUI extends JDialog { JPanel panel1 = new JPanel(); JSlider jSlider1 = new JSlider(); JCheckBox jCheckBox1 = new JCheckBox(); JTextField jTextField1 = new JTextField(); JButton btnCancel = new JButton(); JButton btnOK = new JButton(); JLabel jLabel1 = new JLabel(); public BufferUI(Frame frame, String title, boolean modal) { super(frame, title, modal); try { buildUI(); pack(); } catch (Exception ex) { ex.printStackTrace(); } } public BufferUI() { this(null, "", false); } private void buildUI() throws Exception { panel1.setLayout(null); this.getContentPane().setLayout(null); panel1.setBounds(new Rectangle(-1, 10, 400, 291)); jSlider1.setMaximum(10); jSlider1.setMinimum(0); jSlider1.setValue(1); java.util.Hashtable labelTable = jSlider1.createStandardLabels(10, 0); jSlider1.setLabelTable(labelTable); jSlider1.setMinorTickSpacing(1); jSlider1.setPaintLabels(true); jSlider1.setPaintTicks(true); jSlider1.setMinimumSize(new Dimension(36, 32)); jSlider1.setBounds(new Rectangle(21, 37, 244, 40)); jCheckBox1.setToolTipText(""); jCheckBox1.setText("Save buffer to shapefile"); jCheckBox1.setBounds(new Rectangle(21, 101, 164, 23)); jTextField1.setText("jTextField1"); jTextField1.setBounds(new Rectangle(21, 134, 242, 25)); jTextField1.setText(getOutputDir() + File.separator + "TemporaryBufferShapefile.shp"); this.setModal(true); // Action for the Cancel button... btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btnCancel_actionPerformed(evt); } }); // Action for the OK button... btnOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btnOK_actionPerformed(evt); } }); btnCancel.setBounds(new Rectangle(114, 186, 75, 26)); btnCancel.setText("Cancel"); btnOK.setBounds(new Rectangle(211, 187, 77, 25)); btnOK.setText("OK"); jLabel1.setText("Set buffer distance"); jLabel1.setBounds(new Rectangle(21, 17, 133, 15)); panel1.add(jSlider1, null); panel1.add(jLabel1, null); panel1.add(jCheckBox1, null); panel1.add(jTextField1, null); panel1.add(btnOK, null); panel1.add(btnCancel, null); this.getContentPane().add(panel1, null); } /** * Convenience method to generate an output directory based on the operating * system that the sample is being executed on. * * @return A path to the new directory is return */ private String getOutputDir() { String userDir; //Get the operating systems user profile or home location depending //on which operating system this sample is executed on. if(System.getProperty("os.name").toLowerCase().indexOf("win") > -1){ userDir = System.getenv("UserProfile"); }else{ userDir = System.getenv("HOME"); } String outputDir = userDir + File.separator + "arcgis_sample_output"; System.out.println("Creating output directory - " + outputDir); new File(outputDir).mkdir(); return outputDir; } public String getDistance() { return new String(jSlider1.getValue() + ".0"); } public boolean saveBuffer() { return jCheckBox1.isSelected(); } void btnCancel_actionPerformed(ActionEvent e) { this.dispose(); } void btnOK_actionPerformed(ActionEvent e) { doBuffer(getDistance()); if (saveBuffer()) { doSaveBuffer(jTextField1.getText()); } this.dispose(); } } }