[Schmitzm-commits] r307 - in trunk/src: org/geotools/gui/swing org/geotools/renderer/shape schmitzm/geotools/io schmitzm/geotools/styling schmitzm/io schmitzm/swing
scm-commit@wald.intevation.org
scm-commit at wald.intevation.org
Thu Aug 20 15:49:52 CEST 2009
Author: alfonx
Date: 2009-08-20 15:49:50 +0200 (Thu, 20 Aug 2009)
New Revision: 307
Modified:
trunk/src/org/geotools/gui/swing/JMapPane.java
trunk/src/org/geotools/renderer/shape/TransitionShapefileRenderer.java
trunk/src/schmitzm/geotools/io/GeoImportUtil.java
trunk/src/schmitzm/geotools/styling/StylingUtil.java
trunk/src/schmitzm/io/IOUtil.java
trunk/src/schmitzm/swing/SwingUtil.java
Log:
* GP-Feature: Futher patched our Shapefilerender (= TransitionRenderer in SCHMITZM) to also support spatial quad tree index from JARs. It used a "isLocal" method that only checked for file:// protocoll, and not for jar://... protocoll
* GP-Bugfix: Fixed a problem with .cpg files.. they have been set to the system default when saving the atlas.
* The rendering of vectors should generally be faster now... especially in exported atlases
* Organized-IMports
* Better handling of calls to SingleInstanceListener.newActivation: the splashscreen is now shown and the windows brought to front.
* AV-Feature: After switching from/to anti-aliased rendering, the waiting cursor appears above the map correctly now.
Modified: trunk/src/org/geotools/gui/swing/JMapPane.java
===================================================================
--- trunk/src/org/geotools/gui/swing/JMapPane.java 2009-08-19 18:30:50 UTC (rev 306)
+++ trunk/src/org/geotools/gui/swing/JMapPane.java 2009-08-20 13:49:50 UTC (rev 307)
@@ -277,7 +277,7 @@
* @param context
* - the map context to display
*/
- public JMapPane(GTRenderer render, MapContext context) {
+ public JMapPane(final GTRenderer render, final MapContext context) {
this(null, true, render, context);
}
@@ -293,8 +293,8 @@
* @param context
* - what to draw
*/
- public JMapPane(LayoutManager layout, boolean isDoubleBuffered,
- GTRenderer render, MapContext context) {
+ public JMapPane(final LayoutManager layout, final boolean isDoubleBuffered,
+ final GTRenderer render, final MapContext context) {
super(layout, isDoubleBuffered);
ff = (FilterFactory2) org.geotools.factory.CommonFactoryFinder
@@ -328,8 +328,11 @@
return renderer;
}
- public void setRenderer(GTRenderer renderer) {
+ public void setRenderer(final GTRenderer renderer) {
Map hints = new HashMap();
+
+ this.renderer = renderer;
+
if (renderer instanceof StreamingRenderer || renderer instanceof TransitionShapefileRenderer) {
hints = renderer.getRendererHints();
if (hints == null) {
@@ -341,16 +344,19 @@
} else {
hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
}
+
+ hints.put("memoryPreloadingEnabled", Boolean.TRUE);
+
renderer.setRendererHints(hints);
}
- this.renderer = renderer;
// this.highlightRenderer = new StreamingRenderer();
// this.selectionRenderer = new StreamingRenderer();
- hints.put("memoryPreloadingEnabled", Boolean.FALSE);
// highlightRenderer.setRendererHints(hints);
// selectionRenderer.setRendererHints(hints);
+
+// renderer.setRendererHints(hints);
if (this.context != null) {
this.renderer.setContext(this.context);
@@ -361,7 +367,7 @@
return context;
}
- public void setContext(MapContext context) {
+ public void setContext(final MapContext context) {
if (this.context != null) {
this.context.removeMapLayerListListener(this);
}
@@ -381,7 +387,7 @@
return mapArea;
}
- public void setMapArea(Envelope mapArea) {
+ public void setMapArea(final Envelope mapArea) {
this.mapArea = mapArea;
}
@@ -389,7 +395,7 @@
return state;
}
- public void setState(int state) {
+ public void setState(final int state) {
this.state = state;
// System.out.println("State: " + state);
@@ -399,7 +405,7 @@
return zoomFactor;
}
- public void setZoomFactor(double zoomFactor) {
+ public void setZoomFactor(final double zoomFactor) {
this.zoomFactor = zoomFactor;
}
@@ -407,7 +413,7 @@
return selectionLayer;
}
- public void setSelectionLayer(MapLayer selectionLayer) {
+ public void setSelectionLayer(final MapLayer selectionLayer) {
this.selectionLayer = selectionLayer;
if (selectionManager != null) {
selectionManager.setSelectionLayer(selectionLayer);
@@ -418,7 +424,7 @@
return highlight;
}
- public void setHighlight(boolean highlight) {
+ public void setHighlight(final boolean highlight) {
this.highlight = highlight;
}
@@ -426,7 +432,7 @@
return highlightLayer;
}
- public void setHighlightLayer(MapLayer highlightLayer) {
+ public void setHighlightLayer(final MapLayer highlightLayer) {
this.highlightLayer = highlightLayer;
if (highlightManager != null) {
@@ -438,7 +444,7 @@
return highlightManager;
}
- public void setHighlightManager(HighlightManager highlightManager) {
+ public void setHighlightManager(final HighlightManager highlightManager) {
this.highlightManager = highlightManager;
this.highlightManager.addHighlightChangeListener(this);
this.addMouseMotionListener(this.highlightManager);
@@ -448,7 +454,7 @@
return lineHighlightStyle;
}
- public void setLineHighlightStyle(Style lineHighlightStyle) {
+ public void setLineHighlightStyle(final Style lineHighlightStyle) {
this.lineHighlightStyle = lineHighlightStyle;
}
@@ -456,7 +462,7 @@
return lineSelectionStyle;
}
- public void setLineSelectionStyle(Style lineSelectionStyle) {
+ public void setLineSelectionStyle(final Style lineSelectionStyle) {
this.lineSelectionStyle = lineSelectionStyle;
}
@@ -464,7 +470,7 @@
return pointHighlightStyle;
}
- public void setPointHighlightStyle(Style pointHighlightStyle) {
+ public void setPointHighlightStyle(final Style pointHighlightStyle) {
this.pointHighlightStyle = pointHighlightStyle;
}
@@ -472,7 +478,7 @@
return pointSelectionStyle;
}
- public void setPointSelectionStyle(Style pointSelectionStyle) {
+ public void setPointSelectionStyle(final Style pointSelectionStyle) {
this.pointSelectionStyle = pointSelectionStyle;
}
@@ -480,7 +486,7 @@
return polygonHighlightStyle;
}
- public void setPolygonHighlightStyle(Style polygonHighlightStyle) {
+ public void setPolygonHighlightStyle(final Style polygonHighlightStyle) {
this.polygonHighlightStyle = polygonHighlightStyle;
}
@@ -488,25 +494,25 @@
return polygonSelectionStyle;
}
- public void setPolygonSelectionStyle(Style polygonSelectionStyle) {
+ public void setPolygonSelectionStyle(final Style polygonSelectionStyle) {
this.polygonSelectionStyle = polygonSelectionStyle;
}
- protected void paintComponent(Graphics g) {
+ protected void paintComponent(final Graphics g) {
super.paintComponent(g);
if ((renderer == null) || (mapArea == null)) {
return;
}
- Rectangle r = getBounds();
- Rectangle dr = new Rectangle(r.width, r.height);
+ final Rectangle r = getBounds();
+ final Rectangle dr = new Rectangle(r.width, r.height);
if (!r.equals(oldRect) || reset) {
if (!r.equals(oldRect) && (mapArea == null)) {
try {
mapArea = context.getLayerBounds();
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -536,9 +542,10 @@
baseImage = new BufferedImage(dr.width, dr.height,
BufferedImage.TYPE_INT_ARGB);
- Graphics2D ig = baseImage.createGraphics();
+ final Graphics2D ig = baseImage.createGraphics();
/* System.out.println("rendering"); */
- renderer.setContext(context);
+ if (renderer.getContext() != null)
+ renderer.setContext(context);
labelCache.clear(); // work around anoying labelcache bug
// draw the map
@@ -580,7 +587,7 @@
selectImage = new BufferedImage(dr.width, dr.height,
BufferedImage.TYPE_INT_ARGB);
- Graphics2D ig = selectImage.createGraphics();
+ final Graphics2D ig = selectImage.createGraphics();
/* System.out.println("rendering selection"); */
selectionRenderer.paint((Graphics2D) ig, dr, mapArea);
@@ -610,7 +617,7 @@
highlightStyle = lineHighlightStyle;
}
- MapContext highlightContext = new DefaultMapContext(
+ final MapContext highlightContext = new DefaultMapContext(
DefaultGeographicCRS.WGS84);
highlightContext.addLayer(highlightFeature, highlightStyle);
@@ -621,16 +628,16 @@
}
}
- private Envelope fixAspectRatio(Rectangle r, Envelope mapArea) {
+ private Envelope fixAspectRatio(final Rectangle r, final Envelope mapArea) {
- double mapWidth = mapArea.getWidth(); /* get the extent of the map */
- double mapHeight = mapArea.getHeight();
- double scaleX = r.getWidth() / mapArea.getWidth(); /*
+ final double mapWidth = mapArea.getWidth(); /* get the extent of the map */
+ final double mapHeight = mapArea.getHeight();
+ final double scaleX = r.getWidth() / mapArea.getWidth(); /*
* calculate the new
* scale
*/
- double scaleY = r.getHeight() / mapArea.getHeight();
+ final double scaleY = r.getHeight() / mapArea.getHeight();
double scale = 1.0; // stupid compiler!
if (scaleX < scaleY) { /* pick the smaller scale */
@@ -640,8 +647,8 @@
}
/* calculate the difference in width and height of the new extent */
- double deltaX = /* Math.abs */((r.getWidth() / scale) - mapWidth);
- double deltaY = /* Math.abs */((r.getHeight() / scale) - mapHeight);
+ final double deltaX = /* Math.abs */((r.getWidth() / scale) - mapWidth);
+ final double deltaY = /* Math.abs */((r.getHeight() / scale) - mapHeight);
/*
* System.out.println("delta x " + deltaX);
@@ -649,17 +656,17 @@
*/
/* create the new extent */
- Coordinate ll = new Coordinate(mapArea.getMinX() - (deltaX / 2.0),
+ final Coordinate ll = new Coordinate(mapArea.getMinX() - (deltaX / 2.0),
mapArea.getMinY() - (deltaY / 2.0));
- Coordinate ur = new Coordinate(mapArea.getMaxX() + (deltaX / 2.0),
+ final Coordinate ur = new Coordinate(mapArea.getMaxX() + (deltaX / 2.0),
mapArea.getMaxY() + (deltaY / 2.0));
return new Envelope(ll, ur);
}
- public void doSelection(double x, double y, MapLayer layer) {
+ public void doSelection(final double x, final double y, final MapLayer layer) {
- Geometry geometry = gf.createPoint(new Coordinate(x, y));
+ final Geometry geometry = gf.createPoint(new Coordinate(x, y));
// org.opengis.geometry.Geometry geometry = new Point();
@@ -674,7 +681,7 @@
* - the index of the layer to search
* @throws IndexOutOfBoundsException
*/
- private void findFeature(Geometry geometry, MapLayer layer)
+ private void findFeature(final Geometry geometry, final MapLayer layer)
throws IndexOutOfBoundsException {
org.opengis.filter.spatial.BinarySpatialOperator f = null;
@@ -697,7 +704,7 @@
selectionManager.selectionChanged(this, f);
}
- } catch (IllegalFilterException e) {
+ } catch (final IllegalFilterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -726,30 +733,30 @@
* = (Feature) fi.next(); System.out.println("selected " +
* feat.getAttribute("STATE_NAME")); }
*/
- } catch (IllegalFilterException e) {
+ } catch (final IllegalFilterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
- public void mouseClicked(MouseEvent e) {
+ public void mouseClicked(final MouseEvent e) {
if (mapArea == null) return;
// System.out.println("before area "+mapArea+"\nw:"+mapArea.getWidth()+"
// h:"+mapArea.getHeight());
- Rectangle bounds = this.getBounds();
- double x = (double) (e.getX());
- double y = (double) (e.getY());
- double width = mapArea.getWidth();
- double height = mapArea.getHeight();
+ final Rectangle bounds = this.getBounds();
+ final double x = (double) (e.getX());
+ final double y = (double) (e.getY());
+ final double width = mapArea.getWidth();
+ final double height = mapArea.getHeight();
// xulu.sc
// double width2 = mapArea.getWidth() / 2.0;
// double height2 = mapArea.getHeight() / 2.0;
- double width2 = width / 2.0;
- double height2 = height / 2.0;
+ final double width2 = width / 2.0;
+ final double height2 = height / 2.0;
// xulu.ec
- double mapX = ((x * width) / (double) bounds.width) + mapArea.getMinX();
- double mapY = (((bounds.getHeight() - y) * height) / (double) bounds.height)
+ final double mapX = ((x * width) / (double) bounds.width) + mapArea.getMinX();
+ final double mapY = (((bounds.getHeight() - y) * height) / (double) bounds.height)
+ mapArea.getMinY();
/*
@@ -789,9 +796,9 @@
return;
}
- Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY
+ final Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY
- (height2 / zlevel));
- Coordinate ur = new Coordinate(mapX + (width2 / zlevel), mapY
+ final Coordinate ur = new Coordinate(mapX + (width2 / zlevel), mapY
+ (height2 / zlevel));
// xulu.sc SK: Check for min/max scale
// mapArea = new Envelope(ll, ur);
@@ -806,22 +813,22 @@
repaint();
}
- public void mouseEntered(MouseEvent e) {
+ public void mouseEntered(final MouseEvent e) {
}
- public void mouseExited(MouseEvent e) {
+ public void mouseExited(final MouseEvent e) {
}
- public void mousePressed(MouseEvent e) {
+ public void mousePressed(final MouseEvent e) {
startX = e.getX();
startY = e.getY();
lastX = 0;
lastY = 0;
}
- public void mouseReleased(MouseEvent e) {
- int endX = e.getX();
- int endY = e.getY();
+ public void mouseReleased(final MouseEvent e) {
+ final int endX = e.getX();
+ final int endY = e.getY();
processDrag(startX, startY, endX, endY, e);
lastX = 0;
@@ -833,10 +840,10 @@
panning_started = false;
}
- public void mouseDragged(MouseEvent e) {
- Graphics graphics = this.getGraphics();
- int x = e.getX();
- int y = e.getY();
+ public void mouseDragged(final MouseEvent e) {
+ final Graphics graphics = this.getGraphics();
+ final int x = e.getX();
+ final int y = e.getY();
if ((state == JMapPane.Pan)
|| ((e.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
@@ -850,8 +857,8 @@
// move the image with the mouse
if ((lastX > 0) && (lastY > 0)) {
- int dx = lastX - startX;
- int dy = lastY - startY;
+ final int dx = lastX - startX;
+ final int dy = lastY - startY;
// System.out.println("translate "+dx+","+dy);
final Graphics2D g2 = panningImage.createGraphics();
g2.setBackground(new Color(240, 240, 240)); // TODO richtige
@@ -884,23 +891,23 @@
} else if (state == JMapPane.Select && selectionLayer != null) {
// construct a new bbox filter
- Rectangle bounds = this.getBounds();
+ final Rectangle bounds = this.getBounds();
- double mapWidth = mapArea.getWidth();
- double mapHeight = mapArea.getHeight();
+ final double mapWidth = mapArea.getWidth();
+ final double mapHeight = mapArea.getHeight();
- double x1 = ((this.startX * mapWidth) / (double) bounds.width)
+ final double x1 = ((this.startX * mapWidth) / (double) bounds.width)
+ mapArea.getMinX();
- double y1 = (((bounds.getHeight() - this.startY) * mapHeight) / (double) bounds.height)
+ final double y1 = (((bounds.getHeight() - this.startY) * mapHeight) / (double) bounds.height)
+ mapArea.getMinY();
- double x2 = ((x * mapWidth) / (double) bounds.width)
+ final double x2 = ((x * mapWidth) / (double) bounds.width)
+ mapArea.getMinX();
- double y2 = (((bounds.getHeight() - y) * mapHeight) / (double) bounds.height)
+ final double y2 = (((bounds.getHeight() - y) * mapHeight) / (double) bounds.height)
+ mapArea.getMinY();
- double left = Math.min(x1, x2);
- double right = Math.max(x1, x2);
- double bottom = Math.min(y1, y2);
- double top = Math.max(y1, y2);
+ final double left = Math.min(x1, x2);
+ final double right = Math.max(x1, x2);
+ final double bottom = Math.min(y1, y2);
+ final double top = Math.max(y1, y2);
String name = selectionLayer.getFeatureSource().getSchema()
.getDefaultGeometry().getName();
@@ -908,7 +915,7 @@
if (name == "") {
name = "the_geom";
}
- Filter bb = ff.bbox(ff.property(name), left, bottom, right, top,
+ final Filter bb = ff.bbox(ff.property(name), left, bottom, right, top,
getContext().getCoordinateReferenceSystem().toString());
if (selectionManager != null) {
selectionManager.selectionChanged(this, bb);
@@ -932,7 +939,7 @@
// private void processDrag(int x1, int y1, int x2, int y2) {
// sk.ce
protected void processDrag(final int x1, final int y1, final int x2,
- final int y2, MouseEvent e) {
+ final int y2, final MouseEvent e) {
/****
* If no layer is availabe we dont want a NullPointerException
@@ -951,38 +958,38 @@
return;
}
- Rectangle bounds = this.getBounds();
+ final Rectangle bounds = this.getBounds();
- double mapWidth = mapArea.getWidth();
- double mapHeight = mapArea.getHeight();
+ final double mapWidth = mapArea.getWidth();
+ final double mapHeight = mapArea.getHeight();
- double startX = ((x1 * mapWidth) / (double) bounds.width)
+ final double startX = ((x1 * mapWidth) / (double) bounds.width)
+ mapArea.getMinX();
- double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)
+ final double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)
+ mapArea.getMinY();
- double endX = ((x2 * mapWidth) / (double) bounds.width)
+ final double endX = ((x2 * mapWidth) / (double) bounds.width)
+ mapArea.getMinX();
- double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)
+ final double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)
+ mapArea.getMinY();
if ((state == JMapPane.Pan) || (e.getButton() == MouseEvent.BUTTON3)) {
// move the image with the mouse
// calculate X offsets from start point to the end Point
- double deltaX1 = endX - startX;
+ final double deltaX1 = endX - startX;
// System.out.println("deltaX " + deltaX1);
// new edges
- double left = mapArea.getMinX() - deltaX1;
- double right = mapArea.getMaxX() - deltaX1;
+ final double left = mapArea.getMinX() - deltaX1;
+ final double right = mapArea.getMaxX() - deltaX1;
// now for Y
- double deltaY1 = endY - startY;
+ final double deltaY1 = endY - startY;
// System.out.println("deltaY " + deltaY1);
- double bottom = mapArea.getMinY() - deltaY1;
- double top = mapArea.getMaxY() - deltaY1;
- Coordinate ll = new Coordinate(left, bottom);
- Coordinate ur = new Coordinate(right, top);
+ final double bottom = mapArea.getMinY() - deltaY1;
+ final double top = mapArea.getMaxY() - deltaY1;
+ final Coordinate ll = new Coordinate(left, bottom);
+ final Coordinate ur = new Coordinate(right, top);
// xulu.sc
// mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));
setMapArea(fixAspectRatio(this.getBounds(), new Envelope(ll, ur)));
@@ -997,12 +1004,12 @@
drawRectangle(this.getGraphics());
// make the dragged rectangle (in map coords) the new BBOX
- double left = Math.min(startX, endX);
- double right = Math.max(startX, endX);
- double bottom = Math.min(startY, endY);
- double top = Math.max(startY, endY);
- Coordinate ll = new Coordinate(left, bottom);
- Coordinate ur = new Coordinate(right, top);
+ final double left = Math.min(startX, endX);
+ final double right = Math.max(startX, endX);
+ final double bottom = Math.min(startY, endY);
+ final double top = Math.max(startY, endY);
+ final Coordinate ll = new Coordinate(left, bottom);
+ final Coordinate ur = new Coordinate(right, top);
// xulu.sc
// mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));
@@ -1026,23 +1033,23 @@
drawRectangle(this.getGraphics());
// make the dragged rectangle in screen coords the new map size?
- double left = Math.min(startX, endX);
- double right = Math.max(startX, endX);
- double bottom = Math.min(startY, endY);
- double top = Math.max(startY, endY);
- double nWidth = (mapWidth * mapWidth) / (right - left);
- double nHeight = (mapHeight * mapHeight) / (top - bottom);
- double deltaX1 = left - mapArea.getMinX();
- double nDeltaX1 = (deltaX1 * nWidth) / mapWidth;
- double deltaY1 = bottom - mapArea.getMinY();
- double nDeltaY1 = (deltaY1 * nHeight) / mapHeight;
- Coordinate ll = new Coordinate(mapArea.getMinX() - nDeltaX1,
+ final double left = Math.min(startX, endX);
+ final double right = Math.max(startX, endX);
+ final double bottom = Math.min(startY, endY);
+ final double top = Math.max(startY, endY);
+ final double nWidth = (mapWidth * mapWidth) / (right - left);
+ final double nHeight = (mapHeight * mapHeight) / (top - bottom);
+ final double deltaX1 = left - mapArea.getMinX();
+ final double nDeltaX1 = (deltaX1 * nWidth) / mapWidth;
+ final double deltaY1 = bottom - mapArea.getMinY();
+ final double nDeltaY1 = (deltaY1 * nHeight) / mapHeight;
+ final Coordinate ll = new Coordinate(mapArea.getMinX() - nDeltaX1,
mapArea.getMinY() - nDeltaY1);
- double deltaX2 = mapArea.getMaxX() - right;
- double nDeltaX2 = (deltaX2 * nWidth) / mapWidth;
- double deltaY2 = mapArea.getMaxY() - top;
- double nDeltaY2 = (deltaY2 * nHeight) / mapHeight;
- Coordinate ur = new Coordinate(mapArea.getMaxX() + nDeltaX2,
+ final double deltaX2 = mapArea.getMaxX() - right;
+ final double nDeltaX2 = (deltaX2 * nWidth) / mapWidth;
+ final double deltaY2 = mapArea.getMaxY() - top;
+ final double nDeltaY2 = (deltaY2 * nHeight) / mapHeight;
+ final Coordinate ur = new Coordinate(mapArea.getMaxX() + nDeltaX2,
mapArea.getMaxY() + nDeltaY2);
// xulu.sc
// mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));
@@ -1050,10 +1057,10 @@
// xulu.ec
} else if (state == JMapPane.Select && selectionLayer != null) {
- double left = Math.min(startX, endX);
- double right = Math.max(startX, endX);
- double bottom = Math.min(startY, endY);
- double top = Math.max(startY, endY);
+ final double left = Math.min(startX, endX);
+ final double right = Math.max(startX, endX);
+ final double bottom = Math.min(startY, endY);
+ final double top = Math.max(startY, endY);
String name = selectionLayer.getFeatureSource().getSchema()
.getDefaultGeometry().getLocalName();
@@ -1061,7 +1068,7 @@
if (name == "") {
name = "the_geom";
}
- Filter bb = ff.bbox(ff.property(name), left, bottom, right, top,
+ final Filter bb = ff.bbox(ff.property(name), left, bottom, right, top,
getContext().getCoordinateReferenceSystem().toString());
// System.out.println(bb.toString());
if (selectionManager != null) {
@@ -1084,23 +1091,23 @@
return clickable;
}
- private org.geotools.styling.Style setupStyle(int type, Color color) {
- StyleFactory sf = org.geotools.factory.CommonFactoryFinder
+ private org.geotools.styling.Style setupStyle(final int type, final Color color) {
+ final StyleFactory sf = org.geotools.factory.CommonFactoryFinder
.getStyleFactory(null);
- StyleBuilder sb = new StyleBuilder();
+ final StyleBuilder sb = new StyleBuilder();
org.geotools.styling.Style s = sf.createStyle();
s.setTitle("selection");
// TODO parameterise the color
- PolygonSymbolizer ps = sb.createPolygonSymbolizer(color);
+ final PolygonSymbolizer ps = sb.createPolygonSymbolizer(color);
ps.setStroke(sb.createStroke(color));
- LineSymbolizer ls = sb.createLineSymbolizer(color);
- Graphic h = sb.createGraphic();
+ final LineSymbolizer ls = sb.createLineSymbolizer(color);
+ final Graphic h = sb.createGraphic();
h.setMarks(new Mark[] { sb.createMark("square", color) });
- PointSymbolizer pts = sb.createPointSymbolizer(h);
+ final PointSymbolizer pts = sb.createPointSymbolizer(h);
// Rule r = sb.createRule(new Symbolizer[]{ps,ls,pts});
switch (type) {
@@ -1121,12 +1128,12 @@
return s;
}
- public void highlightChanged(HighlightChangedEvent e) {
- org.opengis.filter.Filter f = e.getFilter();
+ public void highlightChanged(final HighlightChangedEvent e) {
+ final org.opengis.filter.Filter f = e.getFilter();
try {
highlightFeature = highlightLayer.getFeatureSource().getFeatures(f);
- } catch (IOException e1) {
+ } catch (final IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
@@ -1134,8 +1141,8 @@
repaint();
}
- public void propertyChange(PropertyChangeEvent evt) {
- String prop = evt.getPropertyName();
+ public void propertyChange(final PropertyChangeEvent evt) {
+ final String prop = evt.getPropertyName();
if (prop.equalsIgnoreCase("crs")) {
context.setAreaOfInterest(context.getAreaOfInterest(),
@@ -1147,11 +1154,11 @@
return reset;
}
- public void setReset(boolean reset) {
+ public void setReset(final boolean reset) {
this.reset = reset;
}
- public void layerAdded(MapLayerListEvent event) {
+ public void layerAdded(final MapLayerListEvent event) {
changed = true;
if (context.getLayers().length == 1) { // the first one
@@ -1163,7 +1170,7 @@
if (mapArea == null)
mapArea = context.getLayerBounds();
// xulu.ec
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -1174,30 +1181,30 @@
repaint();
}
- public void layerRemoved(MapLayerListEvent event) {
+ public void layerRemoved(final MapLayerListEvent event) {
changed = true;
repaint();
}
- public void layerChanged(MapLayerListEvent event) {
+ public void layerChanged(final MapLayerListEvent event) {
changed = true;
// System.out.println("layer changed - repaint");
repaint();
}
- public void layerMoved(MapLayerListEvent event) {
+ public void layerMoved(final MapLayerListEvent event) {
changed = true;
repaint();
}
- protected void drawRectangle(Graphics graphics) {
+ protected void drawRectangle(final Graphics graphics) {
// undraw last box/draw new box
- int left = Math.min(startX, lastX);
- int right = Math.max(startX, lastX);
- int top = Math.max(startY, lastY);
- int bottom = Math.min(startY, lastY);
- int width = right - left;
- int height = top - bottom;
+ final int left = Math.min(startX, lastX);
+ final int right = Math.max(startX, lastX);
+ final int top = Math.max(startY, lastY);
+ final int bottom = Math.min(startY, lastY);
+ final int width = right - left;
+ final int height = top - bottom;
// System.out.println("drawing rect("+left+","+bottom+","+ width+","+
// height+")");
graphics.drawRect(left, bottom, width, height);
@@ -1209,18 +1216,18 @@
*
* @param clickable
*/
- public void setClickable(boolean clickable) {
+ public void setClickable(final boolean clickable) {
this.clickable = clickable;
}
- public void mouseMoved(MouseEvent e) {
+ public void mouseMoved(final MouseEvent e) {
}
public FeatureCollection getSelection() {
return selection;
}
- public void setSelection(FeatureCollection selection) {
+ public void setSelection(final FeatureCollection selection) {
this.selection = selection;
repaint();
}
@@ -1232,13 +1239,13 @@
* org.geotools.gui.swing.event.SelectionChangeListener#selectionChanged
* (org.geotools.gui.swing.event.SelectionChangedEvent)
*/
- public void selectionChanged(SelectionChangedEvent e) {
+ public void selectionChanged(final SelectionChangedEvent e) {
try {
selection = selectionLayer.getFeatureSource().getFeatures(
e.getFilter());
repaint();
- } catch (IOException e1) {
+ } catch (final IOException e1) {
e1.printStackTrace();
}
}
@@ -1247,7 +1254,7 @@
return selectionManager;
}
- public void setSelectionManager(SelectionManager selectionManager) {
+ public void setSelectionManager(final SelectionManager selectionManager) {
this.selectionManager = selectionManager;
this.selectionManager.addSelectionChangeListener(this);
@@ -1277,9 +1284,9 @@
*/
env = fixAspectRatio(this.getBounds(), env);
- double scale = env.getWidth() / getWidth();
- double centerX = env.getMinX() + env.getWidth() / 2.;
- double centerY = env.getMinY() + env.getHeight() / 2.;
+ final double scale = env.getWidth() / getWidth();
+ final double centerX = env.getMinX() + env.getWidth() / 2.;
+ final double centerY = env.getMinY() + env.getHeight() / 2.;
double newWidth2;
double newHeight2;
if (scale < getMaxZoomScale()) {
@@ -1301,9 +1308,9 @@
return env;
}
- Coordinate ll = new Coordinate(centerX - newWidth2, centerY
+ final Coordinate ll = new Coordinate(centerX - newWidth2, centerY
- newHeight2);
- Coordinate ur = new Coordinate(centerX + newWidth2, centerY
+ final Coordinate ur = new Coordinate(centerX + newWidth2, centerY
+ newHeight2);
return new Envelope(ll, ur);
@@ -1338,7 +1345,7 @@
* @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
* Krüger</a>
*/
- public void setMaxZoomScale(Double maxZoomScale) {
+ public void setMaxZoomScale(final Double maxZoomScale) {
// System.out.println("setting max scale to "+maxZoomScale);
this.maxZoomScale = maxZoomScale;
}
@@ -1350,7 +1357,7 @@
* @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
* Krüger</a>
*/
- public void setMinZoomScale(Double minZoomScale) {
+ public void setMinZoomScale(final Double minZoomScale) {
this.minZoomScale = minZoomScale;
}
// xulu.en
Modified: trunk/src/org/geotools/renderer/shape/TransitionShapefileRenderer.java
===================================================================
--- trunk/src/org/geotools/renderer/shape/TransitionShapefileRenderer.java 2009-08-19 18:30:50 UTC (rev 306)
+++ trunk/src/org/geotools/renderer/shape/TransitionShapefileRenderer.java 2009-08-20 13:49:50 UTC (rev 307)
@@ -23,7 +23,6 @@
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
-import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
@@ -55,6 +54,7 @@
import org.geotools.data.shapefile.shp.ShapeType;
import org.geotools.data.shapefile.shp.ShapefileReader;
import org.geotools.data.shapefile.shp.ShapefileReader.Record;
+import org.geotools.factory.FactoryConfigurationError;
import org.geotools.feature.AttributeType;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureType;
@@ -102,6 +102,7 @@
import org.opengis.referencing.operation.TransformException;
import schmitzm.geotools.feature.FeatureOperationTreeFilter;
+import schmitzm.io.IOUtil;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
@@ -125,9 +126,12 @@
* /src/org/geotools/renderer/shape/ShapefileRenderer.java $
*/
public class TransitionShapefileRenderer implements GTRenderer {
- public static final Logger LOGGER = org.geotools.util.logging.Logging
+ public static final Logger logGt = org.geotools.util.logging.Logging
.getLogger("org.geotools.renderer.shape");
+ org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger
+ .getLogger(TransitionShapefileRenderer.class);
+
/** Tolerance used to compare doubles for equality */
private static final double TOLERANCE = 1e-6;
private static final GeometryFactory geomFactory = new GeometryFactory(
@@ -159,7 +163,7 @@
*/
public static final String SCALE_OGC = "OGC";
- private String scaleComputationMethodDEFAULT = SCALE_ACCURATE;
+ private final String scaleComputationMethodDEFAULT = SCALE_ACCURATE;
static {
COORDS = new Coordinate[5];
COORDS[0] = new Coordinate(0.0, 0.0);
@@ -189,12 +193,12 @@
private RenderingHints hints;
/** Factory that will resolve symbolizers into rendered styles */
- private SLDStyleFactory styleFactory = new SLDStyleFactory();
+ private final SLDStyleFactory styleFactory = new SLDStyleFactory();
private boolean renderingStopRequested;
private boolean concatTransforms;
private MapContext context;
LabelCache labelCache = new LabelCacheDefault();
- private ListenerList renderListeners = new ListenerList();
+ private final ListenerList renderListeners = new ListenerList();
boolean caching = false;
private double scaleDenominator;
DbaseFileHeader dbfheader;
@@ -209,7 +213,7 @@
/** The painter class we use to depict shapes onto the screen */
private StyledShapePainter painter = new StyledShapePainter(labelCache);
- private Map decimators = new HashMap();
+ private final Map decimators = new HashMap();
/**
* Text will be rendered using the usual calls
@@ -232,7 +236,7 @@
* TEXT_RENDERING_STRING
*/
public static final String TEXT_RENDERING_KEY = "textRenderingMethod";
- private String textRenderingModeDEFAULT = TEXT_RENDERING_STRING;
+ private final String textRenderingModeDEFAULT = TEXT_RENDERING_STRING;
public static final String LABEL_CACHE_KEY = "labelCache";
public static final String FORCE_CRS_KEY = "forceCRS";
@@ -256,37 +260,39 @@
*/
private Map rendererHints = null;
- public TransitionShapefileRenderer(MapContext context) {
+ public TransitionShapefileRenderer(final MapContext context) {
+// LOGGER.debug("new tr instanciated with context");
setContext(context);
}
public TransitionShapefileRenderer() {
+// LOGGER.debug("new tr instanciated without context");
}
- public void paint(Graphics2D graphics, Rectangle paintArea,
- ReferencedEnvelope mapArea) {
+ public void paint(final Graphics2D graphics, final Rectangle paintArea,
+ final ReferencedEnvelope mapArea) {
if (mapArea == null || paintArea == null) {
- LOGGER.info("renderer passed null arguments");
+ logGt.info("renderer passed null arguments");
return;
} // Other arguments get checked later
paint(graphics, paintArea, mapArea, RendererUtilities
.worldToScreenTransform(mapArea, paintArea));
}
- private DbaseFileHeader getDBFHeader(ShapefileDataStore ds) {
+ private DbaseFileHeader getDBFHeader(final ShapefileDataStore ds) {
DbaseFileReader reader = null;
try {
reader = ShapefileRendererUtil.getDBFReader(ds);
return reader.getHeader();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -296,63 +302,63 @@
return null;
}
- private void processStylers(Graphics2D graphics,
- ShapefileDataStore datastore, Query query, Envelope bbox,
- Rectangle screenSize, MathTransform mt, Style style,
- IndexInfo info, Transaction transaction, String layerId)
+ private void processStylers(final Graphics2D graphics,
+ final ShapefileDataStore datastore, final Query query, final Envelope bbox,
+ final Rectangle screenSize, final MathTransform mt, final Style style,
+ final IndexInfo info, final Transaction transaction, final String layerId)
throws IOException {
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.fine("processing " + style.getFeatureTypeStyles().length
+ if (logGt.isLoggable(Level.FINE)) {
+ logGt.fine("processing " + style.getFeatureTypeStyles().length
+ " stylers");
}
- FeatureTypeStyle[] featureStylers = style.getFeatureTypeStyles();
+ final FeatureTypeStyle[] featureStylers = style.getFeatureTypeStyles();
FeatureType type;
try {
type = createFeatureType(query, style, datastore);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
return;
}
for (int i = 0; i < featureStylers.length; i++) {
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.fine("processing style " + i);
+ if (logGt.isLoggable(Level.FINE)) {
+ logGt.fine("processing style " + i);
}
- FeatureTypeStyle fts = featureStylers[i];
- String typeName = datastore.getSchema().getTypeName();
+ final FeatureTypeStyle fts = featureStylers[i];
+ final String typeName = datastore.getSchema().getTypeName();
if ((typeName != null)
&& (datastore.getSchema().isDescendedFrom(null,
fts.getFeatureTypeName()) || typeName
.equalsIgnoreCase(fts.getFeatureTypeName()))) {
// get applicable rules at the current scale
- Rule[] rules = fts.getRules();
- List ruleList = new ArrayList();
- List elseRuleList = new ArrayList();
+ final Rule[] rules = fts.getRules();
+ final List ruleList = new ArrayList();
+ final List elseRuleList = new ArrayList();
// TODO process filter for geometry expressions and restrict
// bbox further based on
// the result
for (int j = 0; j < rules.length; j++) {
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.fine("processing rule " + j);
+ if (logGt.isLoggable(Level.FINE)) {
+ logGt.fine("processing rule " + j);
}
Rule r = rules[j];
// make copy so I don't accidentally modify style
- DuplicatingStyleVisitor duplicator = new DuplicatingStyleVisitor();
+ final DuplicatingStyleVisitor duplicator = new DuplicatingStyleVisitor();
r.accept(duplicator);
r = (Rule) duplicator.getCopy();
if (r.getFilter() != null) {
// now reproject the geometries in filter because geoms
// are retrieved projected to screen space
- FilterTransformer transformer = new FilterTransformer(
+ final FilterTransformer transformer = new FilterTransformer(
mt);
r.setFilter((Filter) r.getFilter().accept(transformer,
null));
@@ -370,10 +376,10 @@
// TODO: find a better way to declare the scale ranges so that
// we
// get style caching also between multiple rendering runs
- NumberRange scaleRange = new NumberRange(scaleDenominator,
+ final NumberRange scaleRange = new NumberRange(scaleDenominator,
scaleDenominator);
- Set modifiedFIDs = processTransaction(graphics, bbox, mt,
+ final Set modifiedFIDs = processTransaction(graphics, bbox, mt,
datastore, transaction, typeName, query, ruleList,
elseRuleList, scaleRange, layerId);
@@ -386,15 +392,15 @@
}
}
- private Set processTransaction(Graphics2D graphics, Envelope bbox,
- MathTransform transform, DataStore ds, Transaction transaction,
- String typename, Query query, List ruleList, List elseRuleList,
- NumberRange scaleRange, String layerId) {
+ private Set processTransaction(final Graphics2D graphics, final Envelope bbox,
+ final MathTransform transform, final DataStore ds, final Transaction transaction,
+ final String typename, final Query query, final List ruleList, final List elseRuleList,
+ final NumberRange scaleRange, final String layerId) {
if (transaction == Transaction.AUTO_COMMIT) {
return Collections.EMPTY_SET;
}
- TransactionStateDiff state = (TransactionStateDiff) transaction
+ final TransactionStateDiff state = (TransactionStateDiff) transaction
.getState(ds);
if (state == null) {
@@ -411,7 +417,7 @@
modified = diff.modified2;
added = diff.added;
fids = new HashSet();
- } catch (IOException e) {
+ } catch (final IOException e) {
fids = Collections.EMPTY_SET;
return fids;
}
@@ -428,7 +434,7 @@
boolean doElse = true;
if (modifiedIter.hasNext()) {
- String fid = (String) modifiedIter.next();
+ final String fid = (String) modifiedIter.next();
feature = (Feature) modified.get(fid);
fids.add(fid);
} else {
@@ -440,77 +446,77 @@
if (feature != TransactionStateDiff.NULL) {
// applicable rules
- for (Iterator it = ruleList.iterator(); it.hasNext();) {
- Rule r = (Rule) it.next();
+ for (final Iterator it = ruleList.iterator(); it.hasNext();) {
+ final Rule r = (Rule) it.next();
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("applying rule: " + r.toString());
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("applying rule: " + r.toString());
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("this rule applies ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("this rule applies ...");
}
- Filter filter = r.getFilter();
+ final Filter filter = r.getFilter();
if ((filter == null) || filter.evaluate(feature)) {
doElse = false;
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("processing Symobolizer ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("processing Symobolizer ...");
}
- Symbolizer[] symbolizers = r.getSymbolizers();
+ final Symbolizer[] symbolizers = r.getSymbolizers();
try {
processSymbolizers(graphics, feature,
symbolizers, scaleRange, transform,
layerId);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
continue;
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("... done!");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("... done!");
}
}
}
if (doElse) {
// rules with an else filter
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("rules with an else filter");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("rules with an else filter");
}
- for (Iterator it = elseRuleList.iterator(); it
+ for (final Iterator it = elseRuleList.iterator(); it
.hasNext();) {
- Rule r = (Rule) it.next();
- Symbolizer[] symbolizers = r.getSymbolizers();
+ final Rule r = (Rule) it.next();
+ final Symbolizer[] symbolizers = r.getSymbolizers();
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("processing Symobolizer ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("processing Symobolizer ...");
}
try {
processSymbolizers(graphics, feature,
symbolizers, scaleRange, transform,
layerId);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
continue;
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("... done!");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("... done!");
}
}
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("feature rendered event ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("feature rendered event ...");
}
}
}
@@ -519,11 +525,11 @@
return fids;
}
- private void processShapefile(Graphics2D graphics,
- ShapefileDataStore datastore, Envelope bbox, Rectangle screenSize,
- MathTransform mt, IndexInfo info, FeatureType type, Query query,
- List ruleList, List elseRuleList, Set modifiedFIDs,
- NumberRange scaleRange, String layerId) throws IOException {
+ private void processShapefile(final Graphics2D graphics,
+ final ShapefileDataStore datastore, final Envelope bbox, final Rectangle screenSize,
+ final MathTransform mt, final IndexInfo info, final FeatureType type, final Query query,
+ final List ruleList, final List elseRuleList, final Set modifiedFIDs,
+ final NumberRange scaleRange, final String layerId) throws IOException {
IndexedDbaseFileReader dbfreader = null;
// don't waste time processing the dbf file if the only attribute loades
@@ -531,27 +537,27 @@
if (type.getAttributeCount() > 1) {
try {
dbfreader = ShapefileRendererUtil.getDBFReader(datastore);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
}
}
- OpacityFinder opacityFinder = new OpacityFinder(
+ final OpacityFinder opacityFinder = new OpacityFinder(
getAcceptableSymbolizers(type.getDefaultGeometry()));
- for (Iterator iter = ruleList.iterator(); iter.hasNext();) {
- Rule rule = (Rule) iter.next();
+ for (final Iterator iter = ruleList.iterator(); iter.hasNext();) {
+ final Rule rule = (Rule) iter.next();
rule.accept(opacityFinder);
}
IndexInfo.Reader shpreader = null;
- boolean useJTS = true;
+ final boolean useJTS = true;
try {
shpreader = new IndexInfo.Reader(info, ShapefileRendererUtil
.getShpReader(datastore, bbox, screenSize, mt,
opacityFinder.hasOpacity, useJTS), bbox);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
return;
}
@@ -560,7 +566,7 @@
try {
fidReader = ShapefileRendererUtil
.getFidReader(datastore, shpreader);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
return;
}
@@ -578,11 +584,11 @@
boolean doElse = true;
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.fine("trying to read geometry ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.fine("trying to read geometry ...");
}
- String nextFid = fidReader.next();
+ final String nextFid = fidReader.next();
if (modifiedFIDs.contains(nextFid)) {
shpreader.next();
if (dbfreader != null
@@ -592,19 +598,19 @@
}
if (dbfreader != null && dbfreader.IsRandomAccessEnabled())
dbfreader.goTo(shpreader.getRecordNumber());
- ShapefileReader.Record record = shpreader.next();
+ final ShapefileReader.Record record = shpreader.next();
- Object geom = record.shape();
+ final Object geom = record.shape();
if (geom == null) {
- LOGGER.finest("skipping geometry");
+ logGt.finest("skipping geometry");
if (dbfreader != null
&& !dbfreader.IsRandomAccessEnabled())
dbfreader.skip();
continue;
}
- Feature feature = createFeature(type, record, dbfreader,
+ final Feature feature = createFeature(type, record, dbfreader,
nextFid);
if (!query.getFilter().evaluate(feature))
continue;
@@ -613,74 +619,74 @@
break;
}
- if (LOGGER.isLoggable(Level.FINEST)) {
- LOGGER.finest("... done: " + geom.toString());
+ if (logGt.isLoggable(Level.FINEST)) {
+ logGt.finest("... done: " + geom.toString());
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.fine("... done: " + type.getTypeName());
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.fine("... done: " + type.getTypeName());
}
// applicable rules
- for (Iterator it = ruleList.iterator(); it.hasNext();) {
- Rule r = (Rule) it.next();
+ for (final Iterator it = ruleList.iterator(); it.hasNext();) {
+ final Rule r = (Rule) it.next();
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("applying rule: " + r.toString());
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("applying rule: " + r.toString());
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("this rule applies ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("this rule applies ...");
}
- Filter filter = r.getFilter();
+ final Filter filter = r.getFilter();
if ((filter == null) || filter.evaluate(feature)) {
doElse = false;
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("processing Symobolizer ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("processing Symobolizer ...");
}
- Symbolizer[] symbolizers = r.getSymbolizers();
+ final Symbolizer[] symbolizers = r.getSymbolizers();
processSymbolizers(graphics, feature, geom,
symbolizers, scaleRange, useJTS, layerId);
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("... done!");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("... done!");
}
}
}
if (doElse) {
// rules with an else filter
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("rules with an else filter");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("rules with an else filter");
}
- for (Iterator it = elseRuleList.iterator(); it
+ for (final Iterator it = elseRuleList.iterator(); it
.hasNext();) {
- Rule r = (Rule) it.next();
- Symbolizer[] symbolizers = r.getSymbolizers();
+ final Rule r = (Rule) it.next();
+ final Symbolizer[] symbolizers = r.getSymbolizers();
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("processing Symobolizer ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("processing Symobolizer ...");
}
processSymbolizers(graphics, feature, geom,
symbolizers, scaleRange, useJTS, layerId);
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("... done!");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("... done!");
}
}
}
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("feature rendered event ...");
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("feature rendered event ...");
}
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
}
}
@@ -703,7 +709,7 @@
}
private Class[] getAcceptableSymbolizers(
- GeometryAttributeType defaultGeometry) {
+ final GeometryAttributeType defaultGeometry) {
if (Polygon.class.isAssignableFrom(defaultGeometry.getType())
|| MultiPolygon.class.isAssignableFrom(defaultGeometry
.getType())) {
@@ -714,16 +720,16 @@
return new Class[] { PointSymbolizer.class, LineSymbolizer.class };
}
- Feature createFeature(FeatureType type, Record record,
- DbaseFileReader dbfreader, String id) throws Exception {
+ Feature createFeature(final FeatureType type, final Record record,
+ final DbaseFileReader dbfreader, final String id) throws Exception {
if (type.getAttributeCount() == 1) {
return type.create(new Object[] { getGeom(record.shape(), type
.getDefaultGeometry()) }, id);
} else {
- DbaseFileHeader header = dbfreader.getHeader();
+ final DbaseFileHeader header = dbfreader.getHeader();
- Object[] all = dbfreader.readEntry();
- Object[] values = new Object[type.getAttributeCount()];
+ final Object[] all = dbfreader.readEntry();
+ final Object[] values = new Object[type.getAttributeCount()];
for (int i = 0; i < (values.length - 1); i++) {
values[i] = all[attributeIndexing[i]];
@@ -750,7 +756,7 @@
* GeometryAttributeType used to determine default value
* @return provided geom or default value if null
*/
- private Object getGeom(Object geom, GeometryAttributeType defaultGeometry) {
+ private Object getGeom(final Object geom, final GeometryAttributeType defaultGeometry) {
if (geom instanceof Geometry) {
return geom;
}
@@ -765,7 +771,7 @@
* @return placeholder to use as a default while waiting for a real
* geometry.
*/
- private Object getGeom(GeometryAttributeType defaultGeometry) {
+ private Object getGeom(final GeometryAttributeType defaultGeometry) {
if (MultiPolygon.class.isAssignableFrom(defaultGeometry.getType())) {
return MULTI_POLYGON_GEOM;
} else if (MultiLineString.class.isAssignableFrom(defaultGeometry
@@ -777,7 +783,7 @@
return MULTI_POINT_GEOM;
}
return null; // we don't have a good default value - null will need to
- // do
+ // do
}
/**
@@ -791,12 +797,12 @@
* @throws FactoryConfigurationError
* @throws SchemaException
*/
- FeatureType createFeatureType(Query query, Style style,
- ShapefileDataStore ds) throws SchemaException, IOException {
- FeatureType schema = ds.getSchema();
- String[] attributes = findStyleAttributes((query == null) ? Query.ALL
+ FeatureType createFeatureType(final Query query, final Style style,
+ final ShapefileDataStore ds) throws SchemaException, IOException {
+ final FeatureType schema = ds.getSchema();
+ final String[] attributes = findStyleAttributes((query == null) ? Query.ALL
: query, style, schema);
- AttributeType[] types = new AttributeType[attributes.length];
+ final AttributeType[] types = new AttributeType[attributes.length];
attributeIndexing = new int[attributes.length];
if (attributes.length == 1
@@ -818,7 +824,7 @@
}
}
- FeatureType type = FeatureTypeBuilder.newFeatureType(types, schema
+ final FeatureType type = FeatureTypeBuilder.newFeatureType(types, schema
.getTypeName(), schema.getNamespace(), false, null, schema
.getDefaultGeometry());
@@ -838,14 +844,14 @@
* @return the minimun set of attribute names needed to render
* <code>layer</code>
*/
- private String[] findStyleAttributes(final Query query, Style style,
- FeatureType schema) {
- StyleAttributeExtractor sae = new StyleAttributeExtractor() {
- public void visit(Rule rule) {
+ private String[] findStyleAttributes(final Query query, final Style style,
+ final FeatureType schema) {
+ final StyleAttributeExtractor sae = new StyleAttributeExtractor() {
+ public void visit(final Rule rule) {
- DuplicatingStyleVisitor dupeStyleVisitor = new DuplicatingStyleVisitor();
+ final DuplicatingStyleVisitor dupeStyleVisitor = new DuplicatingStyleVisitor();
dupeStyleVisitor.visit(rule);
- Rule clone = (Rule) dupeStyleVisitor.getCopy();
+ final Rule clone = (Rule) dupeStyleVisitor.getCopy();
super.visit(clone);
}
@@ -853,9 +859,9 @@
sae.visit(style);
- FilterAttributeExtractor qae = new FilterAttributeExtractor();
+ final FilterAttributeExtractor qae = new FilterAttributeExtractor();
query.getFilter().accept(qae, null);
- Set ftsAttributes = new HashSet(sae.getAttributeNameSet());
+ final Set ftsAttributes = new HashSet(sae.getAttributeNameSet());
ftsAttributes.addAll(qae.getAttributeNameSet());
// the code following assumes we won't extract the default geometry, and
// that's
@@ -875,12 +881,12 @@
* @param scaleRange
* @param layerId
*/
- private void processSymbolizers(Graphics2D graphics, Feature feature,
- Object geom, Symbolizer[] symbolizers, NumberRange scaleRange,
- boolean isJTS, String layerId) {
+ private void processSymbolizers(final Graphics2D graphics, final Feature feature,
+ final Object geom, final Symbolizer[] symbolizers, final NumberRange scaleRange,
+ final boolean isJTS, final String layerId) {
for (int m = 0; m < symbolizers.length; m++) {
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("applying symbolizer " + symbolizers[m]);
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("applying symbolizer " + symbolizers[m]);
}
if (renderingStopRequested) {
@@ -893,13 +899,13 @@
feature, new LiteShape2(feature
.getDefaultGeometry(), null, null, false,
false), scaleRange);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
}
} else {
Shape shape;
try {
- Style2D style = styleFactory.createStyle(feature,
+ final Style2D style = styleFactory.createStyle(feature,
symbolizers[m], scaleRange);
if (isJTS) {
Geometry g;
@@ -921,7 +927,7 @@
painter.paint(graphics, shape, style, scaleDenominator);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
}
}
@@ -952,13 +958,13 @@
*/
private void processSymbolizers(final Graphics2D graphics,
final Feature feature, final Symbolizer[] symbolizers,
- Range scaleRange, MathTransform transform, String layerId)
+ final Range scaleRange, final MathTransform transform, final String layerId)
throws TransformException, FactoryException {
LiteShape2 shape;
for (int m = 0; m < symbolizers.length; m++) {
- if (LOGGER.isLoggable(Level.FINER)) {
- LOGGER.finer("applying symbolizer " + symbolizers[m]);
+ if (logGt.isLoggable(Level.FINER)) {
+ logGt.finer("applying symbolizer " + symbolizers[m]);
}
Geometry g = feature.getDefaultGeometry();
@@ -970,7 +976,7 @@
labelCache.put(layerId, (TextSymbolizer) symbolizers[m],
feature, shape, scaleRange);
} else {
- Style2D style = styleFactory.createStyle(feature,
+ final Style2D style = styleFactory.createStyle(feature,
symbolizers[m], scaleRange);
painter.paint(graphics, shape, style, scaleDenominator);
}
@@ -987,7 +993,7 @@
* @return
* @throws org.opengis.referencing.operation.NoninvertibleTransformException
*/
- private Decimator getDecimator(MathTransform mathTransform)
+ private Decimator getDecimator(final MathTransform mathTransform)
throws org.opengis.referencing.operation.NoninvertibleTransformException {
Decimator decimator = null;
@@ -1082,7 +1088,7 @@
* @param geom
* @return
*/
- private Shape getShape(SimpleGeometry geom) {
+ private Shape getShape(final SimpleGeometry geom) {
if ((geom.type == ShapeType.ARC) || (geom.type == ShapeType.ARCM)
|| (geom.type == ShapeType.ARCZ)) {
return new MultiLineShape(geom);
@@ -1112,7 +1118,7 @@
* The rule
* @return true if the scale is compatible with the rule settings
*/
- private boolean isWithInScale(Rule r) {
+ private boolean isWithInScale(final Rule r) {
return ((r.getMinScaleDenominator() - TOLERANCE) <= scaleDenominator)
&& ((r.getMaxScaleDenominator() + TOLERANCE) > scaleDenominator);
}
@@ -1124,7 +1130,7 @@
* the listener to add.
* @see RenderListener
*/
- public void addRenderListener(RenderListener listener) {
+ public void addRenderListener(final RenderListener listener) {
renderListeners.add(listener);
}
@@ -1135,24 +1141,24 @@
* the listener to remove.
* @see RenderListener
*/
- public void removeRenderListener(RenderListener listener) {
+ public void removeRenderListener(final RenderListener listener) {
renderListeners.remove(listener);
}
- private void fireFeatureRenderedEvent(Feature feature) {
- Object[] objects = renderListeners.getListeners();
+ private void fireFeatureRenderedEvent(final Feature feature) {
+ final Object[] objects = renderListeners.getListeners();
for (int i = 0; i < objects.length; i++) {
- RenderListener listener = (RenderListener) objects[i];
+ final RenderListener listener = (RenderListener) objects[i];
listener.featureRenderer(feature);
}
}
- private void fireErrorEvent(Exception e) {
- Object[] objects = renderListeners.getListeners();
+ private void fireErrorEvent(final Exception e) {
+ final Object[] objects = renderListeners.getListeners();
for (int i = 0; i < objects.length; i++) {
- RenderListener listener = (RenderListener) objects[i];
+ final RenderListener listener = (RenderListener) objects[i];
listener.errorOccurred(e);
}
}
@@ -1163,7 +1169,7 @@
* @param scaleDenominator
* New value of property scaleDenominator.
*/
- protected void setScaleDenominator(double scaleDenominator) {
+ protected void setScaleDenominator(final double scaleDenominator) {
this.scaleDenominator = scaleDenominator;
}
@@ -1192,7 +1198,7 @@
* @param caching
* The caching to set.
*/
- public void setCaching(boolean caching) {
+ public void setCaching(final boolean caching) {
this.caching = caching;
}
@@ -1204,15 +1210,15 @@
return concatTransforms;
}
- public void setConcatTransforms(boolean concatTransforms) {
+ public void setConcatTransforms(final boolean concatTransforms) {
this.concatTransforms = concatTransforms;
}
- public IndexInfo useIndex(ShapefileDataStore ds) throws IOException,
+ public IndexInfo useIndex(final ShapefileDataStore ds) throws IOException,
StoreException {
IndexInfo info;
String filename = null;
- URL url = ShapefileRendererUtil.getshpURL(ds);
+ final URL url = ShapefileRendererUtil.getshpURL(ds);
if (url == null) {
throw new NullPointerException("Null URL for ShapefileDataSource");
@@ -1220,38 +1226,44 @@
try {
filename = java.net.URLDecoder.decode(url.toString(), "US-ASCII");
- } catch (java.io.UnsupportedEncodingException use) {
+ } catch (final java.io.UnsupportedEncodingException use) {
throw new java.net.MalformedURLException("Unable to decode " + url
+ " cause " + use.getMessage());
}
filename = filename.substring(0, filename.length() - 4);
- String grxext = ".grx";
- String qixext = ".qix";
+ final String grxext = ".grx";
+ final String qixext = ".qix";
- if (ds.isLocal()) {
- File grxTree = new File(new URL(filename + grxext).getPath());
- File qixTree = new File(new URL(filename + qixext).getPath());
- URL shx = new URL(filename + ".shx");
+ final boolean local = ds.isLocal();
+ LOGGER.debug("TransitionShapefileRendere is local = " + local
+ + ".. anyway ignoring it.");
+ // if (local) {
+ final URL shx = IOUtil.changeUrlExt(url, "shx");
+ final URL qixTree = IOUtil.changeUrlExt(url, "qix");
+ final URL grxTree = IOUtil.changeUrlExt(url, "grx");
- if (!new File(shx.getPath()).exists()) {
- info = new IndexInfo(IndexInfo.TREE_NONE, null, null);
- } else if (qixTree.exists()) {
- info = new IndexInfo(IndexInfo.QUAD_TREE, new URL(filename
- + qixext), shx);
- LOGGER.fine("Using quad tree");
- } else if (grxTree.exists()) {
- info = new IndexInfo(IndexInfo.R_TREE, new URL(filename
- + grxext), shx);
- LOGGER.fine("Using r-tree");
+ if (!IOUtil.urlExists(shx)) {
+ LOGGER.debug(shx + " doesn exist => no index");
+ info = new IndexInfo(IndexInfo.TREE_NONE, null, null);
+ } else if (IOUtil.urlExists(qixTree)) {
+ info = new IndexInfo(IndexInfo.QUAD_TREE, qixTree, shx);
+ LOGGER.debug("Using quad tree");
+ } else {
+ LOGGER.debug(qixTree + " doesn exist ");
+ if (IOUtil.urlExists(grxTree)) {
+ info = new IndexInfo(IndexInfo.R_TREE, grxTree, shx);
+ LOGGER.debug("Using r-tree");
} else {
+ LOGGER.debug(grxTree + " doesn exist ");
info = new IndexInfo(IndexInfo.TREE_NONE, null, null);
- LOGGER.fine("No indexing");
+ LOGGER.debug("No indexing");
}
- } else {
- info = new IndexInfo(IndexInfo.TREE_NONE, null, null);
}
+ // } else {
+ // info = new IndexInfo(IndexInfo.TREE_NONE, null, null);
+ // }
return info;
}
@@ -1264,19 +1276,19 @@
/**
* @see org.geotools.renderer.lite.RenderListener#featureRenderer(org.geotools.feature.Feature)
*/
- public void featureRenderer(Feature feature) {
+ public void featureRenderer(final Feature feature) {
// do nothing.
}
/**
* @see org.geotools.renderer.lite.RenderListener#errorOccurred(java.lang.Exception)
*/
- public void errorOccurred(Exception e) {
- LOGGER.log(Level.SEVERE, e.getMessage(), e);
+ public void errorOccurred(final Exception e) {
+ logGt.log(Level.SEVERE, e.getMessage(), e);
}
}
- public void setJava2DHints(RenderingHints hints) {
+ public void setJava2DHints(final RenderingHints hints) {
this.hints = hints;
}
@@ -1284,9 +1296,9 @@
return hints;
}
- public void setRendererHints(Map hints) {
+ public void setRendererHints(final Map hints) {
if (hints != null && hints.containsKey(LABEL_CACHE_KEY)) {
- LabelCache cache = (LabelCache) hints.get(LABEL_CACHE_KEY);
+ final LabelCache cache = (LabelCache) hints.get(LABEL_CACHE_KEY);
if (cache == null)
throw new NullPointerException(
"Label_Cache_Hint has a null value for the labelcache");
@@ -1308,11 +1320,11 @@
this.context = context;
- MapLayer[] layers = context.getLayers();
+ final MapLayer[] layers = context.getLayers();
layerIndexInfo = new IndexInfo[layers.length];
for (int i = 0; i < layers.length; i++) {
- DataStore ds = layers[i].getFeatureSource().getDataStore();
+ final DataStore ds = layers[i].getFeatureSource().getDataStore();
if (ds instanceof ShapefileDataStore) {
/**
@@ -1321,17 +1333,18 @@
if (layers[i].getQuery() != null
&& layers[i].getQuery().getFilter() instanceof FeatureOperationTreeFilter) {
layerIndexInfo[i] = STREAMING_RENDERER_INFO;
- LOGGER.info("Fallback to StreamingRenderer because Filter is instanceof FeatureOperationTreeFilter!");
+ logGt
+ .info("Fallback to StreamingRenderer because Filter is instanceof FeatureOperationTreeFilter!");
} else {
- ShapefileDataStore sds = (ShapefileDataStore) ds;
+ final ShapefileDataStore sds = (ShapefileDataStore) ds;
try {
layerIndexInfo[i] = useIndex(sds);
- } catch (Exception e) {
+ } catch (final Exception e) {
layerIndexInfo[i] = new IndexInfo(IndexInfo.TREE_NONE,
null, null);
- LOGGER.fine("Exception while trying to use index"
+ logGt.fine("Exception while trying to use index"
+ e.getLocalizedMessage());
}
}
@@ -1341,10 +1354,10 @@
}
}
- public void paint(Graphics2D graphics, Rectangle paintArea,
- AffineTransform worldToScreen) {
+ public void paint(final Graphics2D graphics, final Rectangle paintArea,
+ final AffineTransform worldToScreen) {
if (worldToScreen == null || paintArea == null) {
- LOGGER.info("renderer passed null arguments");
+ logGt.info("renderer passed null arguments");
return;
} // Other arguments get checked later
// First, create the bbox in real world coordinates
@@ -1353,21 +1366,21 @@
mapArea = RendererUtilities.createMapEnvelope(paintArea,
worldToScreen, getContext().getCoordinateReferenceSystem());
paint(graphics, paintArea, mapArea, worldToScreen);
- } catch (NoninvertibleTransformException e) {
+ } catch (final NoninvertibleTransformException e) {
fireErrorEvent(new Exception(
"Can't create pixel to world transform", e));
}
}
- public void paint(Graphics2D graphics, Rectangle paintArea,
- ReferencedEnvelope envelope, AffineTransform transform) {
+ public void paint(final Graphics2D graphics, final Rectangle paintArea,
+ final ReferencedEnvelope envelope, AffineTransform transform) {
if (hints != null) {
graphics.setRenderingHints(hints);
}
if ((graphics == null) || (paintArea == null)) {
- LOGGER.info("renderer passed null arguments");
+ logGt.info("renderer passed null arguments");
return;
}
@@ -1375,8 +1388,8 @@
// reset the abort flag
renderingStopRequested = false;
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.fine("Affine Transform is " + transform);
+ if (logGt.isLoggable(Level.FINE)) {
+ logGt.fine("Affine Transform is " + transform);
}
/*
@@ -1385,7 +1398,7 @@
* An example of this is the ZoomPane component of the swinggui module.
*/
if (concatTransforms) {
- AffineTransform atg = graphics.getTransform();
+ final AffineTransform atg = graphics.getTransform();
// graphics.setTransform(new AffineTransform());
atg.concatenate(transform);
@@ -1396,33 +1409,33 @@
setScaleDenominator(computeScale(envelope, context
.getCoordinateReferenceSystem(), paintArea,
this.rendererHints));
- } catch (Exception e) // probably either (1) no CRS (2) error xforming
+ } catch (final Exception e) // probably either (1) no CRS (2) error xforming
{
- LOGGER
+ logGt
.throwing(
"RendererUtilities",
"calculateScale(envelope, coordinateReferenceSystem, imageWidth, imageHeight, hints)",
e);
setScaleDenominator(1 / transform.getScaleX()); // DJB old method -
- // the best we can
- // do
+ // the best we can
+ // do
}
- MapLayer[] layers = context.getLayers();
+ final MapLayer[] layers = context.getLayers();
// get detstination CRS
- CoordinateReferenceSystem destinationCrs = context
+ final CoordinateReferenceSystem destinationCrs = context
.getCoordinateReferenceSystem();
labelCache.start();
labelCache.clear();
if (labelCache instanceof LabelCacheDefault) {
- boolean outlineEnabled = TEXT_RENDERING_OUTLINE
+ final boolean outlineEnabled = TEXT_RENDERING_OUTLINE
.equals(getTextRenderingMethod());
((LabelCacheDefault) labelCache)
.setOutlineRenderingEnabled(outlineEnabled);
}
for (int i = 0; i < layers.length; i++) {
- MapLayer currLayer = layers[i];
+ final MapLayer currLayer = layers[i];
if (!currLayer.isVisible()) {
// Only render layer when layer is visible
@@ -1443,7 +1456,7 @@
ReferencedEnvelope bbox = envelope;
try {
- GeometryAttributeType geom = currLayer.getFeatureSource()
+ final GeometryAttributeType geom = currLayer.getFeatureSource()
.getSchema().getDefaultGeometry();
CoordinateReferenceSystem dataCRS;
@@ -1460,9 +1473,9 @@
.createOperation(dataCRS, destinationCrs);
mt = op.getMathTransform();
bbox = bbox.transform(dataCRS, true, 10);
- } catch (Exception e) {
+ } catch (final Exception e) {
fireErrorEvent(e);
- LOGGER
+ logGt
.log(
Level.WARNING,
"Could not reproject the bounding boxes, proceeding in non reprojecting mode",
@@ -1471,7 +1484,7 @@
mt = null;
}
- MathTransform at = ReferencingFactoryFinder
+ final MathTransform at = ReferencingFactoryFinder
.getMathTransformFactory(null).createAffineTransform(
new GeneralMatrix(transform));
@@ -1484,7 +1497,7 @@
// dbfheader must be set so that the attributes required for
// theming can be read in.
- ShapefileDataStore ds = (ShapefileDataStore) currLayer
+ final ShapefileDataStore ds = (ShapefileDataStore) currLayer
.getFeatureSource().getDataStore();
// graphics.setTransform(transform);
@@ -1498,11 +1511,11 @@
.getTransaction();
}
- DefaultQuery query = new DefaultQuery(currLayer.getQuery());
+ final DefaultQuery query = new DefaultQuery(currLayer.getQuery());
if (query.getFilter() != null) {
// now reproject the geometries in filter because geoms are
// retrieved projected to screen space
- FilterTransformer transformer = new FilterTransformer(
+ final FilterTransformer transformer = new FilterTransformer(
dataCRS, destinationCrs, mt);
query.setFilter((Filter) query.getFilter().accept(
transformer, null));
@@ -1521,7 +1534,7 @@
processStylers(graphics, ds, query, bbox, paintArea, mt,
currLayer.getStyle(), layerIndexInfo[i], transaction,
"" + i);
- } catch (Exception exception) {
+ } catch (final Exception exception) {
fireErrorEvent(new Exception("Exception rendering layer "
+ currLayer, exception));
}
@@ -1530,7 +1543,7 @@
}
labelCache.end(graphics, paintArea);
- LOGGER.fine("Style cache hit ratio: " + styleFactory.getHitRatio()
+ logGt.fine("Style cache hit ratio: " + styleFactory.getHitRatio()
+ " , hits " + styleFactory.getHits() + ", requests "
+ styleFactory.getRequests());
}
@@ -1541,7 +1554,7 @@
private String getTextRenderingMethod() {
if (rendererHints == null)
return textRenderingModeDEFAULT;
- String result = (String) rendererHints.get(TEXT_RENDERING_KEY);
+ final String result = (String) rendererHints.get(TEXT_RENDERING_KEY);
if (result == null)
return textRenderingModeDEFAULT;
return result;
@@ -1555,40 +1568,40 @@
private String getScaleComputationMethod() {
if (rendererHints == null)
return scaleComputationMethodDEFAULT;
- String result = (String) rendererHints
+ final String result = (String) rendererHints
.get(SCALE_COMPUTATION_METHOD_KEY);
if (result == null)
return scaleComputationMethodDEFAULT;
return result;
}
- private double computeScale(ReferencedEnvelope envelope,
- CoordinateReferenceSystem crs, Rectangle paintArea, Map hints) {
+ private double computeScale(final ReferencedEnvelope envelope,
+ final CoordinateReferenceSystem crs, final Rectangle paintArea, final Map hints) {
if (getScaleComputationMethod().equals(SCALE_ACCURATE)) {
try {
return RendererUtilities.calculateScale(envelope,
paintArea.width, paintArea.height, hints);
- } catch (Exception e) // probably either (1) no CRS (2) error
- // xforming
+ } catch (final Exception e) // probably either (1) no CRS (2) error
+ // xforming
{
- LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
+ logGt.log(Level.WARNING, e.getLocalizedMessage(), e);
}
}
return RendererUtilities.calculateOGCScale(envelope, paintArea.width,
hints);
}
- private void renderWithStreamingRenderer(MapLayer layer,
- Graphics2D graphics, Rectangle paintArea,
- ReferencedEnvelope envelope, AffineTransform transform) {
+ private void renderWithStreamingRenderer(final MapLayer layer,
+ final Graphics2D graphics, final Rectangle paintArea,
+ final ReferencedEnvelope envelope, final AffineTransform transform) {
MapContext context = null;
try {
context = new DefaultMapContext(new MapLayer[] { layer }, envelope
.getCoordinateReferenceSystem());
- StreamingRenderer renderer = new StreamingRenderer();
+ final StreamingRenderer renderer = new StreamingRenderer();
renderer.setContext(context);
renderer.setJava2DHints(getJava2DHints());
- Map rendererHints2 = new HashMap(
+ final Map rendererHints2 = new HashMap(
getRendererHints() != null ? getRendererHints()
: Collections.EMPTY_MAP);
rendererHints2.put(LABEL_CACHE_KEY, new IntegratingLabelCache(
@@ -1609,7 +1622,7 @@
private CoordinateReferenceSystem getForceCRSHint() {
if (rendererHints == null)
return null;
- Object crs = this.rendererHints.get("forceCRS");
+ final Object crs = this.rendererHints.get("forceCRS");
if (crs instanceof CoordinateReferenceSystem)
return (CoordinateReferenceSystem) crs;
@@ -1619,7 +1632,7 @@
/**
* @deprecated
*/
- public void paint(Graphics2D graphics, Rectangle paintArea, Envelope mapArea) {
+ public void paint(final Graphics2D graphics, final Rectangle paintArea, final Envelope mapArea) {
paint(graphics, paintArea, new ReferencedEnvelope(mapArea, context
.getCoordinateReferenceSystem()));
}
@@ -1627,8 +1640,8 @@
/**
* @deprecated
*/
- public void paint(Graphics2D graphics, Rectangle paintArea,
- Envelope mapArea, AffineTransform worldToScreen) {
+ public void paint(final Graphics2D graphics, final Rectangle paintArea,
+ final Envelope mapArea, final AffineTransform worldToScreen) {
paint(graphics, paintArea, new ReferencedEnvelope(mapArea, context
.getCoordinateReferenceSystem()), worldToScreen);
}
Modified: trunk/src/schmitzm/geotools/io/GeoImportUtil.java
===================================================================
--- trunk/src/schmitzm/geotools/io/GeoImportUtil.java 2009-08-19 18:30:50 UTC (rev 306)
+++ trunk/src/schmitzm/geotools/io/GeoImportUtil.java 2009-08-20 13:49:50 UTC (rev 307)
@@ -79,15 +79,20 @@
/**
* In dieser Klasse sind Funktionen zum Datenimport von Geo-Daten
* zusammengefasst.
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
* @version 1.0
*/
public class GeoImportUtil {
- private static final Logger LOGGER = Logger.getLogger(GeoImportUtil.class.getName());
+ private static final Logger LOGGER = Logger.getLogger(GeoImportUtil.class
+ .getName());
- /** These postfixes are associated with Arc/Info ASCII Grid files
- * TODO .0 habe ich auch schon gesehen. Nut leider kann man das nicht in einen enum packen.
- * */
+ /**
+ * These postfixes are associated with Arc/Info ASCII Grid files TODO .0
+ * habe ich auch schon gesehen. Nut leider kann man das nicht in einen enum
+ * packen.
+ * */
static public enum ARCASCII_POSTFIXES {
arc, dat, ascii, txt, asc, a00
};
@@ -99,12 +104,15 @@
/** These postfixes are associated with ESRI SHape files */
static public enum SHP_POSTFIXES {
- shp, sbx, sbn, dbf, shx,
- qix, fix, // Non-ESRI QuadTree Index stuff
- cpg // Supported by ESRI. Contains the name of codepage used inside the DBF
+ shp, sbx, sbn, dbf, shx, qix, fix, // Non-ESRI QuadTree Index stuff
+ cpg
+ // Supported by ESRI. Contains the name of codepage used inside the DBF
};
- /** These postfixes are associated with ordinary image files, excluding GeoTIFF endings please */
+ /**
+ * These postfixes are associated with ordinary image files, excluding
+ * GeoTIFF endings please
+ */
static public enum IMAGE_POSTFIXES {
png, gif, jpg, jpeg
};
@@ -114,33 +122,36 @@
wld, jgw, pgw, tfw
};
+ /**
+ * Standard-CRS, welches verwendet wird, wenn beim Import kein CRS ermittelt
+ * werden kann (Default: {@link DefaultGeographicCRS#WGS84}).<br>
+ * <b>Achtung:</b><br>
+ * Anwendungen koennen diese Variable gefahrlos ueberschreiben, um ein fuer
+ * die Anwendung adaequates Standard-CRS zu verwenden.
+ */
+ public static CoordinateReferenceSystem DEFAULT_CRS = DefaultGeographicCRS.WGS84;
- /**
- * Standard-CRS, welches verwendet wird, wenn beim Import kein CRS ermittelt
- * werden kann (Default: {@link DefaultGeographicCRS#WGS84}).<br>
- * <b>Achtung:</b><br>
- * Anwendungen koennen diese Variable gefahrlos ueberschreiben, um ein fuer
- * die Anwendung adaequates Standard-CRS zu verwenden.
- */
- public static CoordinateReferenceSystem DEFAULT_CRS = DefaultGeographicCRS.WGS84;
-
- /**
- * Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt
- * (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>)
- * und speichert diese in einer <code>org.geotools.feature.FeatureCollection</code>.<br>
- *
- * @param url {@link URL} to Shape-File
- * @param prjUrl {@link URL} zu .prj Datei des Shape-File
- *
- *
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- *
- * @return {@link FeatureCollection} that was read
- *
- * @throws IOException
- */
- public static FeatureCollection readFeaturesFromShapeURL(URL url,
- URL prjUrl) throws IOException {
+ /**
+ * Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt
+ * (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
+ * speichert diese in einer
+ * <code>org.geotools.feature.FeatureCollection</code>.<br>
+ *
+ * @param url
+ * {@link URL} to Shape-File
+ * @param prjUrl
+ * {@link URL} zu .prj Datei des Shape-File
+ *
+ *
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ *
+ * @return {@link FeatureCollection} that was read
+ *
+ * @throws IOException
+ */
+ public static FeatureCollection readFeaturesFromShapeURL(URL url, URL prjUrl)
+ throws IOException {
ShapefileDataStore store = new ShapefileDataStore(url);
try {
// Testen, ob Projektion ermittelt werden kann, um vorab das
@@ -160,576 +171,719 @@
.getFeatures();
// Create a new DefaultFeatureCollection to allow modifying
- // operations on the collection ("fc" is a DataFeatureCollection, whose
- // add(.) and remove(.) methods do nothing. Furthermore a FIDFeatureReader
- // is used which returns copies of the features, so modifying the attributes
+ // operations on the collection ("fc" is a DataFeatureCollection, whose
+ // add(.) and remove(.) methods do nothing. Furthermore a
+ // FIDFeatureReader
+ // is used which returns copies of the features, so modifying the
+ // attributes
// does not effect the features in the collection!)
- FeatureCollection fc1 = FeatureCollections.newCollection( fc.getID() );
- fc1.addAll( fc );
- fc = fc1;
+ FeatureCollection fc1 = FeatureCollections.newCollection(fc.getID());
+ fc1.addAll(fc);
+ fc = fc1;
- return fc;
+ return fc;
}
-
- /**
- * Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>)
- * und speichert diese in einer
+ /**
+ * Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt
+ * (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
+ * speichert diese in einer
* <code>org.geotools.feature.FeatureCollection</code>.<br>
- *
+ *
* @param file
* Shape-File
* @throws java.lang.Exception
* bei irgendeinem Fehler
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- *
- * TODO Wenn readFeaturesFromShapeURL getestet ist, dann sollte die hiet auf readFeaturesFromShapeURL(file.getURL) umgeleitet werden (SK)
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ *
+ * TODO Wenn readFeaturesFromShapeURL getestet ist, dann sollte die
+ * hiet auf readFeaturesFromShapeURL(file.getURL) umgeleitet werden
+ * (SK)
*/
- public static FeatureCollection readFeaturesFromShapeFile(File file) throws Exception {
- ShapefileDataStore store = new ShapefileDataStore(file.toURI().toURL());
- File prjFile = IOUtil.changeFileExt(file, "prj");
- boolean delPrjFile = false;
- try {
- // Testen, ob Projektion ermittelt werden kann, um vorab das Standard-CRS
- // zu setzen
- String prjString = readProjectionString(prjFile);
- if ( prjString == null || prjString.trim().equals("") )
- throw new FileNotFoundException("No proper prj-File exists: "+file.getName());
- CRS.parseWKT(prjString);
- } catch (FileNotFoundException err) {
- store.forceSchemaCRS(getDEFAULT_CRS());
- LOGGER.warn("No projection found for file "+file.getName()+". Default is used.");
- delPrjFile = true; // von DataStore erzeugte Datei wieder loeschen
- }
- String[] typeNames = store.getTypeNames();
- FeatureCollection fc = store.getFeatureSource(typeNames[0]).getFeatures();
- if ( delPrjFile )
- prjFile.delete();
+ public static FeatureCollection readFeaturesFromShapeFile(File file)
+ throws Exception {
+ ShapefileDataStore store = new ShapefileDataStore(file.toURI().toURL());
+ File prjFile = IOUtil.changeFileExt(file, "prj");
+ boolean delPrjFile = false;
+ try {
+ // Testen, ob Projektion ermittelt werden kann, um vorab das
+ // Standard-CRS
+ // zu setzen
+ String prjString = readProjectionString(prjFile);
+ if (prjString == null || prjString.trim().equals(""))
+ throw new FileNotFoundException("No proper prj-File exists: "
+ + file.getName());
+ CRS.parseWKT(prjString);
+ } catch (FileNotFoundException err) {
+ store.forceSchemaCRS(getDEFAULT_CRS());
+ LOGGER.warn("No projection found for file " + file.getName()
+ + ". Default is used.");
+ delPrjFile = true; // von DataStore erzeugte Datei wieder loeschen
+ }
+ String[] typeNames = store.getTypeNames();
+ FeatureCollection fc = store.getFeatureSource(typeNames[0])
+ .getFeatures();
+ if (delPrjFile)
+ prjFile.delete();
- // Create a new DefaultFeatureCollection to allow modifying
- // operations on the collection ("fc" is a DataFeatureCollection, whose
- // add(.) and remove(.) methods do nothing. Furthermore a FIDFeatureReader
- // is used which returns copies of the features, so modifying the attributes
- // does not effect the features in the collection!)
- FeatureCollection fc1 = FeatureCollections.newCollection( fc.getID() );
- fc1.addAll( fc );
- fc = fc1;
+ // Create a new DefaultFeatureCollection to allow modifying
+ // operations on the collection ("fc" is a DataFeatureCollection, whose
+ // add(.) and remove(.) methods do nothing. Furthermore a
+ // FIDFeatureReader
+ // is used which returns copies of the features, so modifying the
+ // attributes
+ // does not effect the features in the collection!)
+ FeatureCollection fc1 = FeatureCollections.newCollection(fc.getID());
+ fc1.addAll(fc);
+ fc = fc1;
- return fc;
- }
+ return fc;
+ }
+ /**
+ * TODO DOKU
+ *
+ * @param shpURL
+ * @param prjURL
+ * @return
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ * @throws IOException
+ */
+ public static DataStore readDataStoreFromShape(URL shpURL, URL prjURL)
+ throws IOException {
+ Map map = new HashMap();
+ map.put("url", shpURL);
+ map.put("create spatial index", true);
- /**
- * TODO DOKU
- * @param shpURL
- * @param prjURL
- * @return
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- * @throws IOException
- */
- public static DataStore readDataStoreFromShape(URL shpURL, URL prjURL) throws IOException {
- Map map = new HashMap();
- map.put( "url", shpURL );
- map.put( "create spatial index", true );
+ // DataStore dataStore = DataStoreFinder.getDataStore( map );
+ DataStore dataStore = new IndexedShapefileDataStore(shpURL, null,
+ false, true, IndexedShapefileDataStore.TREE_QIX);
+ // DataStore dataStore = new ShapefileDataStore(shpURL);
+ System.out.println("DataStore = " + dataStore.getClass().toString());
+ IndexedShapefileDataStore dataStoreIndex = (IndexedShapefileDataStore) dataStore;
+ System.out.println("indexed = " + dataStoreIndex.isIndexed());
+ System.out.println("memory = " + dataStoreIndex.isMemoryMapped());
+ return dataStore;
+ }
- //DataStore dataStore = DataStoreFinder.getDataStore( map );
- DataStore dataStore = new IndexedShapefileDataStore(shpURL, null, false, true, IndexedShapefileDataStore.TREE_QIX);
- // DataStore dataStore = new ShapefileDataStore(shpURL);
- System.out.println("DataStore = "+dataStore.getClass().toString());
- IndexedShapefileDataStore dataStoreIndex = (IndexedShapefileDataStore)dataStore;
- System.out.println("indexed = "+dataStoreIndex.isIndexed());
- System.out.println("memory = "+dataStoreIndex.isMemoryMapped());
- return dataStore;
- }
-
-
- /**
- * Diese Methode extrahiert saemtliche Geometrien aus einem ShapeFile-Projekt
- * (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>)
- * und speichert diese in einer Liste (Vector) von {@link com.vividsolutions.jts.geom.Geometry}-Objekten.<br>
- * Baut auf folgenden Geotools-Klassen auf:
- * <code>
- * <ul>
- * <li>{@link ShapefileReader org.geotools.data.shapefile.shp.ShapefileReader}</li>
+ /**
+ * Diese Methode extrahiert saemtliche Geometrien aus einem
+ * ShapeFile-Projekt (
+ * <code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
+ * speichert diese in einer Liste (Vector) von
+ * {@link com.vividsolutions.jts.geom.Geometry}-Objekten.<br>
+ * Baut auf folgenden Geotools-Klassen auf: <code>
+ * <ul>
+ * <li>{@link ShapefileReader org.geotools.data.shapefile.shp.ShapefileReader}</li>
* <li>{@link Geometry com.vividsolutions.jts.geom.Geometry}</li>
* </ul>
* </code>
- * @param file Shape-File
- * @throws java.lang.Exception bei irgendeinem Fehler
- */
- public static Vector<Geometry> readGeometriesFromShapeFile(File file) throws Exception {
- FileChannel in = new FileInputStream(file).getChannel();
- ShapefileReader r = new ShapefileReader( in, new Lock() );
- Vector<Geometry> geomList = new Vector<Geometry>();
- for(int i=1; r.hasNext(); i++) {
- // org.geotools.renderer.geom.Geometry shape = (org.geotools.renderer.geom.Geometry) r.nextRecord().shape();
- // org.geotools.geometry.Geometry shape = (org.geotools.geometry.Geometry) r.nextRecord().shape();
- Object obj = r.nextRecord().shape();
- Geometry shape = (Geometry)obj;
- geomList.add(shape);
- }
- r.close();
- return geomList;
- }
+ *
+ * @param file
+ * Shape-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ */
+ public static Vector<Geometry> readGeometriesFromShapeFile(File file)
+ throws Exception {
+ FileChannel in = new FileInputStream(file).getChannel();
+ ShapefileReader r = new ShapefileReader(in, new Lock());
+ Vector<Geometry> geomList = new Vector<Geometry>();
+ for (int i = 1; r.hasNext(); i++) {
+ // org.geotools.renderer.geom.Geometry shape =
+ // (org.geotools.renderer.geom.Geometry) r.nextRecord().shape();
+ // org.geotools.geometry.Geometry shape =
+ // (org.geotools.geometry.Geometry) r.nextRecord().shape();
+ Object obj = r.nextRecord().shape();
+ Geometry shape = (Geometry) obj;
+ geomList.add(shape);
+ }
+ r.close();
+ return geomList;
+ }
- /**
- * Diese Methode importiert ein Raster aus einer Datei im ArcInfoASCII-Grid-Format.
- * Das CRS wird aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition)
- * gelesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS}
- * als CRS verwendet.
- * @param file ASCII-File
- * @throws java.lang.Exception bei irgendeinem Fehler
- * @return {@link GridCoverage2D}
- */
- public static GridCoverage2D readGridFromArcInfoASCII(File file) throws Exception {
- return readGridFromArcInfoASCII(file,null);
- }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im
+ * ArcInfoASCII-Grid-Format. Das CRS wird aus einem prj-File (EPSG-Code
+ * "EPSG:..." oder WKT-Definition) gelesen. Ist dies nicht erfolgreich, wird
+ * {@link #DEFAULT_CRS} als CRS verwendet.
+ *
+ * @param file
+ * ASCII-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @return {@link GridCoverage2D}
+ */
+ public static GridCoverage2D readGridFromArcInfoASCII(File file)
+ throws Exception {
+ return readGridFromArcInfoASCII(file, null);
+ }
- /**
- * Diese Methode importiert ein Raster aus einer Datei im ArcInfoASCII-Grid-Format.
- * Wenn kein CRS angegeben wird, wird versucht das CRS aus einem prj-File
- * (EPSG-Code "EPSG:..." oder WKT-Definition) zu lesen. Ist dies nicht
- * erfolgreich, wird {@link #DEFAULT_CRS} als CRS verwendet.
- * @param file ASCII-File
- * @param crs CoordinateReferenceSystem fuer das Raster (kann {@code null} sein)
- * @throws java.lang.Exception bei irgendeinem Fehler
- * TODO
- */
- public static GridCoverage2D readGridFromArcInfoASCII(File file, CoordinateReferenceSystem crs) throws Exception {
- return readGridFromArcInfoASCII(file.toURI().toURL(), crs);
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im
+ * ArcInfoASCII-Grid-Format. Wenn kein CRS angegeben wird, wird versucht das
+ * CRS aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition) zu
+ * lesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS} als CRS
+ * verwendet.
+ *
+ * @param file
+ * ASCII-File
+ * @param crs
+ * CoordinateReferenceSystem fuer das Raster (kann {@code null}
+ * sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler TODO
+ */
+ public static GridCoverage2D readGridFromArcInfoASCII(File file,
+ CoordinateReferenceSystem crs) throws Exception {
+ return readGridFromArcInfoASCII(file.toURI().toURL(), crs);
-// ArcGridRaster reader = new ArcGridRaster( new BufferedReader( new InputStreamReader( new FileInputStream(file) ) ), false );
-// WritableRaster raster = reader.readRaster();
-// if (crs == null)
-// crs = determineProjection(file);
-//
-//// System.out.println("Position "+reader.getXlCorner()+" / "+reader.getYlCorner());
-//// System.out.println("Size "+reader.getNCols()+" / "+reader.getNRows());
-//// System.out.println("Min/Max "+reader.getMinValue()+" / "+reader.getMaxValue());
-//// System.out.println("NoData "+reader.getNoData());
-//// System.out.println("CellSize "+reader.getCellSize());
-//
-// float x = (float) reader.getXlCorner(); // Suedwestliche Ecke!
-// float y = (float) reader.getYlCorner(); // Suedwestliche Ecke!
-// float w = (float) (reader.getNCols() * reader.getCellSize()); // reale Breite = RasterSpalten * Aufloesung
-// float h = (float) (reader.getNRows() * reader.getCellSize()); // reale Hoehe = RasterZeilen * Aufloesung
-// Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y, w, h));
-//
-// // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten das
-// // Coloring des Rasters nicht klappt.
-// // --> Name der Categories muss (warum auch immer) mit dem Namen
-// // des Rasters uebereinstimmen!!!
-// return new GridCoverageFactory().create("", raster, envelope);
-////
-////=== OHNE ArcGridRaster ===
-////// ArcGridReader reader = new ArcGridReader( new BufferedReader( new InputStreamReader( new FileInputStream(file) ) ));
-//// ArcGridReader reader = new ArcGridReader( file );
-//// return (GridCoverage2D)reader.read(null);
- }
+ // ArcGridRaster reader = new ArcGridRaster( new BufferedReader( new
+ // InputStreamReader( new FileInputStream(file) ) ), false );
+ // WritableRaster raster = reader.readRaster();
+ // if (crs == null)
+ // crs = determineProjection(file);
+ //
+ // //
+ // System.out.println("Position "+reader.getXlCorner()+" / "+reader.getYlCorner());
+ // //
+ // System.out.println("Size "+reader.getNCols()+" / "+reader.getNRows());
+ // //
+ // System.out.println("Min/Max "+reader.getMinValue()+" / "+reader.getMaxValue());
+ // // System.out.println("NoData "+reader.getNoData());
+ // // System.out.println("CellSize "+reader.getCellSize());
+ //
+ // float x = (float) reader.getXlCorner(); // Suedwestliche Ecke!
+ // float y = (float) reader.getYlCorner(); // Suedwestliche Ecke!
+ // float w = (float) (reader.getNCols() * reader.getCellSize()); //
+ // reale Breite = RasterSpalten * Aufloesung
+ // float h = (float) (reader.getNRows() * reader.getCellSize()); //
+ // reale Hoehe = RasterZeilen * Aufloesung
+ // Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y,
+ // w, h));
+ //
+ // // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten
+ // das
+ // // Coloring des Rasters nicht klappt.
+ // // --> Name der Categories muss (warum auch immer) mit dem Namen
+ // // des Rasters uebereinstimmen!!!
+ // return new GridCoverageFactory().create("", raster, envelope);
+ // //
+ // //=== OHNE ArcGridRaster ===
+ // //// ArcGridReader reader = new ArcGridReader( new BufferedReader(
+ // new InputStreamReader( new FileInputStream(file) ) ));
+ // // ArcGridReader reader = new ArcGridReader( file );
+ // // return (GridCoverage2D)reader.read(null);
+ }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im
+ * ArcInfoASCII-Grid-Format. Wenn kein CRS angegeben wird, wird versucht das
+ * CRS aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition) zu
+ * lesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS} als CRS
+ * verwendet.
+ *
+ * @param url
+ * Link to Arc/Info GRID ASCII file
+ * @param crs
+ * CoordinateReferenceSystem fuer das Raster (kann {@code null}
+ * sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ */
+ public static GridCoverage2D readGridFromArcInfoASCII(URL url,
+ CoordinateReferenceSystem crs) throws Exception {
+ ArcGridRaster reader = new ArcGridRaster(new BufferedReader(
+ new InputStreamReader(url.openStream())), false);
+ WritableRaster raster = reader.readRaster();
+ if (crs == null)
+ crs = determineProjection(IOUtil.changeUrlExt(url, "prj"));
- /**
- * Diese Methode importiert ein Raster aus einer Datei im ArcInfoASCII-Grid-Format.
- * Wenn kein CRS angegeben wird, wird versucht das CRS aus einem prj-File
- * (EPSG-Code "EPSG:..." oder WKT-Definition) zu lesen. Ist dies nicht
- * erfolgreich, wird {@link #DEFAULT_CRS} als CRS verwendet.
- * @param url Link to Arc/Info GRID ASCII file
- * @param crs CoordinateReferenceSystem fuer das Raster (kann {@code null} sein)
- * @throws java.lang.Exception bei irgendeinem Fehler
- */
- public static GridCoverage2D readGridFromArcInfoASCII(URL url, CoordinateReferenceSystem crs) throws Exception {
- ArcGridRaster reader = new ArcGridRaster( new BufferedReader( new InputStreamReader(url.openStream()) ), false );
- WritableRaster raster = reader.readRaster();
- if (crs == null)
- crs = determineProjection( IOUtil.changeUrlExt(url,"prj"));
+ LOGGER.debug("Position " + reader.getXlCorner() + " / "
+ + reader.getYlCorner());
+ LOGGER.debug("Size " + reader.getNCols() + " / "
+ + reader.getNRows());
+ LOGGER.debug("Min/Max " + reader.getMinValue() + " / "
+ + reader.getMaxValue());
+ LOGGER.debug("NoData " + reader.getNoData());
+ LOGGER.debug("CellSize " + reader.getCellSize());
-// System.out.println("Position "+reader.getXlCorner()+" / "+reader.getYlCorner());
-// System.out.println("Size "+reader.getNCols()+" / "+reader.getNRows());
-// System.out.println("Min/Max "+reader.getMinValue()+" / "+reader.getMaxValue());
-// System.out.println("NoData "+reader.getNoData());
-// System.out.println("CellSize "+reader.getCellSize());
+ Double x = reader.getXlCorner(); // Suedwestliche Ecke!
+ Double y = reader.getYlCorner(); // Suedwestliche Ecke!
+ if (y.isNaN() || x.isNaN()) {
+ throw new IllegalArgumentException(
+ "The parameters xlCorner and/or ylCorner could not be read. Hint: Check if the file defines 'xlcenter' instead of 'xlcorner'. If so, just replace all 'center' with 'corner' and try again.");
+ }
- float x = (float) reader.getXlCorner(); // Suedwestliche Ecke!
- float y = (float) reader.getYlCorner(); // Suedwestliche Ecke!
- float w = (float) (reader.getNCols() * reader.getCellSize()); // reale Breite = RasterSpalten * Aufloesung
- float h = (float) (reader.getNRows() * reader.getCellSize()); // reale Hoehe = RasterZeilen * Aufloesung
- Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y, w, h));
+ Double w = (reader.getNCols() * reader.getCellSize()); // reale Breite =
+ // RasterSpalten
+ // * Aufloesung
+ Double h = (reader.getNRows() * reader.getCellSize()); // reale Hoehe =
+ // RasterZeilen
+ // * Aufloesung
+ Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Double(x, y,
+ w, h));
- // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten das
- // Coloring des Rasters nicht klappt.
- // --> Name der Categories muss (warum auch immer) mit dem Namen
- // des Rasters uebereinstimmen!!!
- return new GridCoverageFactory().create("", raster, envelope);
-//
-//=== OHNE ArcGridRaster ===
-//// ArcGridReader reader = new ArcGridReader( new BufferedReader( new InputStreamReader( new FileInputStream(file) ) ));
-// ArcGridReader reader = new ArcGridReader( file );
-// return (GridCoverage2D)reader.read(null);
- }
+ // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten das
+ // Coloring des Rasters nicht klappt.
+ // --> Name der Categories muss (warum auch immer) mit dem Namen
+ // des Rasters uebereinstimmen!!!
+ return new GridCoverageFactory().create("", raster, envelope);
+ //
+ // === OHNE ArcGridRaster ===
+ // // ArcGridReader reader = new ArcGridReader( new BufferedReader( new
+ // InputStreamReader( new FileInputStream(file) ) ));
+ // ArcGridReader reader = new ArcGridReader( file );
+ // return (GridCoverage2D)reader.read(null);
+ }
+ /**
+ * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus
+ * einer Datei im GeoTIFF-Format. Zunaechst wird versucht, die
+ * Geo-Informationen (Referenz+CRS) aus den TIFF-Metadaten zu ermitteln. Ist
+ * dies nicht erfolgreich, werden ein gleichnamiges World-File (.tfw) und
+ * Projection-File (.prj) herangezogen (siehe {@link WorldImageReader}).
+ *
+ * @param file
+ * GeoTIFF-File
+ * @param crs
+ * erzwungenes CoordinateReferenceSystem fuer das Raster (kann
+ * {@code null} sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig
+ * (Colorisierung schlaegt fehl!)
+ */
+ public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(
+ File file, CoordinateReferenceSystem crs) throws Exception {
+ // Versuchen Geo-Information aus Tiff zu lesen
+ try {
+ Hints hints = new Hints(null);
+ // Wenn CRS angegeben, dieses durch Hint erzwingen
+ if (crs != null)
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
+ // Reader (mit Metadaten) erzeugen
+ GeoTiffReader reader = new GeoTiffReader(file, hints);
+ // Wenn kein Referenzsystem vorhanden, versuchen ein prj-File zu
+ // verwenden
+ if (reader.getOriginalEnvelope().getCoordinateReferenceSystem() == null) {
+ LOGGER.warn("No projection information found in '"
+ + file.getName() + "'. Using prj-file...");
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM,
+ determineProjection(file));
+ reader = new GeoTiffReader(file, hints);
+ }
+ return reader;
+ } catch (UnsupportedOperationException err) {
+ // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+ } catch (NullPointerException err) {
+ // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+ }
+ // keine Geo-Informationen in Tiff
+ // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile
+ // verwenden
+ LOGGER.warn("No geo information found in '" + file.getName()
+ + "'. Using world- and prj-file...");
+ // @todo check the work of WorldImageReader with colorization!
+ throw new UnsupportedOperationException(
+ "WorldImageReader does not work well, yet... AbstractGridCoverage2DReader can not be created from this Tiff!");
+ // Hints hints = new Hints(null);
+ // // Wenn CRS angegeben, dieses durch Hint erzwingen
+ // if ( crs != null )
+ // hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs );
+ // WorldImageReader reader = new WorldImageReader(file);
+ // return reader;
+ }
+ /**
+ * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus
+ * einer Datei im GeoTIFF-Format.
+ *
+ * @param file
+ * GeoTIFF-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @see #createGridReaderFromGeoTiff(File, CoordinateReferenceSystem)
+ * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig
+ * (Colorisierung schlaegt fehl!)
+ */
+ public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(
+ File file) throws Exception {
+ return createGridReaderFromGeoTiff(file, null);
+ }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
+ *
+ * @param file
+ * GeoTIFF-File
+ * @param crs
+ * erzwungenes CoordinateReferenceSystem fuer das Raster (kann
+ * {@code null} sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @see #createGridReaderFromGeoTiff(File, CoordinateReferenceSystem)
+ */
+ public static GridCoverage2D readGridFromGeoTiff(File file,
+ CoordinateReferenceSystem crs) throws Exception {
+ // return (GridCoverage2D)createGridReaderFromGeoTiff(file,
+ // crs).read(null);
+ GridCoverage2D gc = null;
+ // Versuchen Geo-Information aus Tiff zu lesen
+ try {
+ Hints hints = new Hints(null);
- /**
- * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus einer
- * Datei im GeoTIFF-Format.
- * Zunaechst wird versucht, die Geo-Informationen (Referenz+CRS) aus den
- * TIFF-Metadaten zu ermitteln. Ist dies nicht erfolgreich, werden
- * ein gleichnamiges World-File (.tfw) und Projection-File (.prj)
- * herangezogen (siehe {@link WorldImageReader}).
- * @param file GeoTIFF-File
- * @param crs erzwungenes CoordinateReferenceSystem fuer das Raster (kann {@code null} sein)
- * @throws java.lang.Exception bei irgendeinem Fehler
- * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig (Colorisierung schlaegt fehl!)
- */
- public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(File file, CoordinateReferenceSystem crs) throws Exception {
- // Versuchen Geo-Information aus Tiff zu lesen
- try {
- Hints hints = new Hints(null);
- // Wenn CRS angegeben, dieses durch Hint erzwingen
- if ( crs != null )
- hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs );
- // Reader (mit Metadaten) erzeugen
- GeoTiffReader reader = new GeoTiffReader(file,hints);
- // Wenn kein Referenzsystem vorhanden, versuchen ein prj-File zu verwenden
- if ( reader.getOriginalEnvelope().getCoordinateReferenceSystem() == null ) {
- LOGGER.warn("No projection information found in '"+file.getName()+"'. Using prj-file...");
- hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, determineProjection(file) );
- reader = new GeoTiffReader(file,hints);
- }
- return reader;
- } catch ( UnsupportedOperationException err ) {
- // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
- } catch ( NullPointerException err ) {
- // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
- }
+ // Wenn CRS angegeben, dieses durch Hint erzwingen
+ if (crs != null)
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
+ // Reader (mit Metadaten) erzeugen
+ GeoTiffReader reader = new GeoTiffReader(file, hints);
+ // Wenn kein Referenzsystem vorhanden, versuchen ein prj-File zu
+ // verwenden
+ if (reader.getOriginalEnvelope().getCoordinateReferenceSystem() == null) {
+ LOGGER.warn("No projection information found in '"
+ + file.getName() + "'. Using prj-file...");
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM,
+ determineProjection(file));
+ reader = new GeoTiffReader(file, hints);
+ }
+ gc = (GridCoverage2D) reader.read(null);
+ return gc;
+ } catch (UnsupportedOperationException err) {
+ // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+ // ExceptionMonitor.show(null, err,
+ // "No geoinformation in TIFF, importing it as a normal file. Trying to read it as normal TIFF + Worldfile.");
+ } catch (NullPointerException err) {
+ // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+ }
- // keine Geo-Informationen in Tiff
- // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile verwenden
- LOGGER.warn("No geo information found in '" + file.getName() + "'. Using world- and prj-file...");
- // @todo check the work of WorldImageReader with colorization!
- throw new UnsupportedOperationException("WorldImageReader does not work well, yet... AbstractGridCoverage2DReader can not be created from this Tiff!");
-// Hints hints = new Hints(null);
-// // Wenn CRS angegeben, dieses durch Hint erzwingen
-// if ( crs != null )
-// hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs );
-// WorldImageReader reader = new WorldImageReader(file);
-// return reader;
- }
+ // keine Geo-Informationen in Tiff
+ // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile
+ // verwenden
+ LOGGER.warn("No geo information found in '" + file.getName()
+ + "'. Using world- and prj-file...");
+ BufferedImage im = ImageIO.read(file);
+ if (im == null)
+ throw new IIOException("No image reader found for this image type!");
+ // World-File einlesen
+ File tfw = IOUtil.changeFileExt(file, "tfw");
+ double[] tfwInfo = readWorldFile(tfw);
+ float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite =
+ // RasterSpalten * hor.
+ // Aufloesung
+ float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe =
+ // RasterZeilen *
+ // vert. Aufloesung
+ float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
+ float y = (float) tfwInfo[5] - h; // Suedwestliche Ecke (im tfw-File
+ // steht die Nordwestliche!)
+ // ggf. Projektion einlesen
+ if (crs == null)
+ crs = determineProjection(file);
+ Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y,
+ w, h));
+ // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten das
+ // Coloring des Rasters nicht klappt.
+ // --> Name der Categories muss (warum auch immer) mit dem Namen
+ // des Rasters uebereinstimmen!!!
+ gc = new GridCoverageFactory().create("", im.copyData(null), envelope);
+ return gc;
+ }
- /**
- * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus einer
- * Datei im GeoTIFF-Format.
- * @param file GeoTIFF-File
- * @throws java.lang.Exception bei irgendeinem Fehler
- * @see #createGridReaderFromGeoTiff(File, CoordinateReferenceSystem)
- * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig (Colorisierung schlaegt fehl!)
- */
- public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(File file) throws Exception {
- return createGridReaderFromGeoTiff(file,null);
- }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
+ *
+ * @param file
+ * GeoTIFF-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @see #readGridFromGeoTiff(File, CoordinateReferenceSystem)
+ */
+ public static GridCoverage2D readGridFromGeoTiff(File file)
+ throws Exception {
+ return readGridFromGeoTiff(file, null);
+ }
- /**
- * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
- * @param file GeoTIFF-File
- * @param crs erzwungenes CoordinateReferenceSystem fuer das Raster (kann {@code null} sein)
- * @throws java.lang.Exception bei irgendeinem Fehler
- * @see #createGridReaderFromGeoTiff(File, CoordinateReferenceSystem)
- */
- public static GridCoverage2D readGridFromGeoTiff(File file, CoordinateReferenceSystem crs) throws Exception {
-// return (GridCoverage2D)createGridReaderFromGeoTiff(file, crs).read(null);
- GridCoverage2D gc = null;
- // Versuchen Geo-Information aus Tiff zu lesen
- try {
- Hints hints = new Hints(null);
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im
+ * ArcInfoASCII-Grid-Format. Das CRS wird aus einem prj-File (EPSG-Code
+ * "EPSG:..." oder WKT-Definition) gelesen. Ist dies nicht erfolgreich, wird
+ * {@link #DEFAULT_CRS} als CRS verwendet.
+ *
+ * @param file
+ * ASCII-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ */
+ public static WritableGridRaster readGridRasterFromArcInfoASCII(File file)
+ throws Exception {
+ return readGridRasterFromArcInfoASCII(file, null);
+ }
- // Wenn CRS angegeben, dieses durch Hint erzwingen
- if ( crs != null )
- hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs );
- // Reader (mit Metadaten) erzeugen
- GeoTiffReader reader = new GeoTiffReader(file,hints);
- // Wenn kein Referenzsystem vorhanden, versuchen ein prj-File zu verwenden
- if ( reader.getOriginalEnvelope().getCoordinateReferenceSystem() == null ) {
- LOGGER.warn("No projection information found in '"+file.getName()+"'. Using prj-file...");
- hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, determineProjection(file) );
- reader = new GeoTiffReader(file,hints);
- }
- gc = (GridCoverage2D)reader.read(null);
- return gc;
- } catch ( UnsupportedOperationException err ) {
- // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
-// ExceptionMonitor.show(null, err, "No geoinformation in TIFF, importing it as a normal file. Trying to read it as normal TIFF + Worldfile.");
- } catch ( NullPointerException err ) {
- // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
- }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im
+ * ArcInfoASCII-Grid-Format. Wenn kein CRS angegeben wird, wird versucht das
+ * CRS aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition) zu
+ * lesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS} als CRS
+ * verwendet.
+ *
+ * @param file
+ * ASCII-File
+ * @param crs
+ * CoordinateReferenceSystem fuer das Raster (kann {@code null}
+ * sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ */
+ public static WritableGridRaster readGridRasterFromArcInfoASCII(File file,
+ CoordinateReferenceSystem crs) throws Exception {
+ ArcGridRaster reader = new ArcGridRaster(new BufferedReader(
+ new InputStreamReader(new FileInputStream(file))), false);
+ WritableRaster raster = reader.readRaster();
+ float x = (float) reader.getXlCorner(); // Suedwestliche Ecke!
+ float y = (float) reader.getYlCorner(); // Suedwestliche Ecke!
+ float w = (float) (reader.getNCols() * reader.getCellSize()); // reale
+ // Breite
+ // =
+ // RasterSpalten
+ // *
+ // Aufloesung
+ float h = (float) (reader.getNRows() * reader.getCellSize()); // reale
+ // Hoehe
+ // =
+ // RasterZeilen
+ // *
+ // Aufloesung
+ // Projektion einlesen
+ if (crs == null)
+ crs = determineProjection(file);
+ return new WritableGridRaster(raster,
+ new Rectangle2D.Float(x, y, w, h), crs);
- // keine Geo-Informationen in Tiff
- // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile verwenden
- LOGGER.warn("No geo information found in '" + file.getName() +
- "'. Using world- and prj-file...");
- BufferedImage im = ImageIO.read(file);
- if (im == null)
- throw new IIOException("No image reader found for this image type!");
- // World-File einlesen
- File tfw = IOUtil.changeFileExt(file, "tfw");
- double[] tfwInfo = readWorldFile(tfw);
- float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite = RasterSpalten * hor. Aufloesung
- float h = (float) (im.getHeight() * ( -tfwInfo[3])); // reale Hoehe = RasterZeilen * vert. Aufloesung
- float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
- float y = (float) tfwInfo[5] - h; // Suedwestliche Ecke (im tfw-File steht die Nordwestliche!)
- // ggf. Projektion einlesen
- if (crs == null)
- crs = determineProjection(file);
- Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y, w, h));
- // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten das
- // Coloring des Rasters nicht klappt.
- // --> Name der Categories muss (warum auch immer) mit dem Namen
- // des Rasters uebereinstimmen!!!
- gc = new GridCoverageFactory().create("", im.copyData(null), envelope);
- return gc;
- }
+ // === OHNE ArcGridRaster ===
+ // GridCoverage2D grid = readGridFromArcInfoASCII(null,input);
+ // WritableRaster raster = grid.getRenderedImage().copyData(null);
+ // return( new WritableGridRaster(raster,grid.getEnvelope2D()) );
+ }
- /**
- * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
- * @param file GeoTIFF-File
- * @throws java.lang.Exception bei irgendeinem Fehler
- * @see #readGridFromGeoTiff(File, CoordinateReferenceSystem)
- */
- public static GridCoverage2D readGridFromGeoTiff(File file) throws Exception {
- return readGridFromGeoTiff(file,null);
- }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
+ * Zunaechst wird versucht, die Geo-Informationen (Referenz+CRS) aus den
+ * TIFF-Metadaten zu ermitteln. Ist dies nicht erfolgreich, werden ein
+ * gleichnamiges World-File (.tfw) und Projection-File (.prj) herangezogen.
+ * Als Projektion (.prj) ist sowohl ein EPSG-Code "EPSG:...", als auch eine
+ * WKT-Definition erlaubt. Kann kein CRS ermitteln werden, wird
+ * {@link #DEFAULT_CRS} als CRS verwendet.
+ *
+ * @param file
+ * GeoTIFF-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ */
+ public static WritableGridRaster readGridRasterFromGeoTiff(File file)
+ throws Exception {
+ return readGridRasterFromGeoTiff(file, null);
+ }
- /**
- * Diese Methode importiert ein Raster aus einer Datei im ArcInfoASCII-Grid-Format.
- * Das CRS wird aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition)
- * gelesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS}
- * als CRS verwendet.
- * @param file ASCII-File
- * @throws java.lang.Exception bei irgendeinem Fehler
- */
- public static WritableGridRaster readGridRasterFromArcInfoASCII(File file) throws Exception {
- return readGridRasterFromArcInfoASCII(file,null);
- }
+ /**
+ * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
+ * Zunaechst wird versucht, die Geo-Informationen (Referenz+CRS) aus den
+ * TIFF-Metadaten zu ermitteln. Ist dies nicht erfolgreich, werden ein
+ * gleichnamiges World-File (.tfw) und Projection-File (.prj) herangezogen.
+ * Als Projektion (.prj) ist sowohl ein EPSG-Code "EPSG:...", als auch eine
+ * WKT-Definition erlaubt. Kann kein CRS ermitteln werden, wird
+ * {@link #DEFAULT_CRS} als CRS verwendet.
+ *
+ * @param file
+ * GeoTIFF-File
+ * @param crs
+ * erzwungenes CoordinateReferenceSystem fuer das Raster (kann
+ * {@code null} sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ */
+ public static WritableGridRaster readGridRasterFromGeoTiff(File file,
+ CoordinateReferenceSystem crs) throws Exception {
+ // // GeoTiff-File einlesen
+ // BufferedImage im = ImageIO.read( file );
+ // if ( im == null )
+ // throw new IIOException("No image reader found for this image type!");
+ // // World-File einlesen
+ // File tfw = IOUtil.changeFileExt(file,"tfw");
+ // double[] tfwInfo = readWorldFile(tfw);
+ // // ggf. Projektion einlesen
+ // if (crs == null)
+ // crs = determineProjection(file);
+ //
+ // float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite =
+ // RasterSpalten * hor. Aufloesung
+ // float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe =
+ // RasterZeilen * vert. Aufloesung
+ // float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
+ // float y = (float) tfwInfo[5] - h ; // Suedwestliche Ecke (im tfw-File
+ // steht die Nordwestliche!)
+ //
+ // Rectangle2D env = new Rectangle2D.Float(x,y,w,h);
+ // WritableGridRaster raster = new WritableGridRaster(
+ // im.getData().getDataBuffer().getDataType(),
+ // 0,
+ // 0,
+ // im.getWidth(),
+ // im.getHeight(),
+ // env,
+ // crs
+ // );
+ //
- /**
- * Diese Methode importiert ein Raster aus einer Datei im ArcInfoASCII-Grid-Format.
- * Wenn kein CRS angegeben wird, wird versucht das CRS aus einem prj-File
- * (EPSG-Code "EPSG:..." oder WKT-Definition) zu lesen. Ist dies nicht
- * erfolgreich, wird {@link #DEFAULT_CRS} als CRS verwendet.
- * @param file ASCII-File
- * @param crs CoordinateReferenceSystem fuer das Raster (kann {@code null} sein)
- * @throws java.lang.Exception bei irgendeinem Fehler
- */
- public static WritableGridRaster readGridRasterFromArcInfoASCII(File file, CoordinateReferenceSystem crs) throws Exception {
- ArcGridRaster reader = new ArcGridRaster(new BufferedReader(new InputStreamReader(new FileInputStream(file))),false);
- WritableRaster raster = reader.readRaster();
- float x = (float)reader.getXlCorner(); // Suedwestliche Ecke!
- float y = (float)reader.getYlCorner(); // Suedwestliche Ecke!
- float w = (float)(reader.getNCols() * reader.getCellSize()); // reale Breite = RasterSpalten * Aufloesung
- float h = (float)(reader.getNRows() * reader.getCellSize()); // reale Hoehe = RasterZeilen * Aufloesung
- // Projektion einlesen
- if (crs == null)
- crs = determineProjection(file);
- return new WritableGridRaster(raster, new Rectangle2D.Float(x,y,w,h), crs );
+ GridCoverage2D gc = readGridFromGeoTiff(file, crs);
+ Rectangle2D env = gc.getEnvelope2D();
+ RenderedImage im = gc.getRenderedImage();
+ WritableGridRaster raster = new WritableGridRaster(im.getData()
+ .getDataBuffer().getDataType(), 0, 0, im.getWidth(), im
+ .getHeight(), env, crs);
-//=== OHNE ArcGridRaster ===
-// GridCoverage2D grid = readGridFromArcInfoASCII(null,input);
-// WritableRaster raster = grid.getRenderedImage().copyData(null);
-// return( new WritableGridRaster(raster,grid.getEnvelope2D()) );
- }
+ im.copyData(raster);
- /**
- * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
- * Zunaechst wird versucht, die Geo-Informationen (Referenz+CRS) aus den
- * TIFF-Metadaten zu ermitteln. Ist dies nicht erfolgreich, werden
- * ein gleichnamiges World-File (.tfw) und Projection-File (.prj)
- * herangezogen. Als Projektion (.prj) ist sowohl ein EPSG-Code "EPSG:...",
- * als auch eine WKT-Definition erlaubt. Kann kein CRS ermitteln werden,
- * wird {@link #DEFAULT_CRS} als CRS verwendet.
- * @param file GeoTIFF-File
- * @throws java.lang.Exception bei irgendeinem Fehler
- */
- public static WritableGridRaster readGridRasterFromGeoTiff(File file) throws Exception {
- return readGridRasterFromGeoTiff(file,null);
- }
+ return raster;
+ }
- /**
- * Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
- * Zunaechst wird versucht, die Geo-Informationen (Referenz+CRS) aus den
- * TIFF-Metadaten zu ermitteln. Ist dies nicht erfolgreich, werden
- * ein gleichnamiges World-File (.tfw) und Projection-File (.prj)
- * herangezogen. Als Projektion (.prj) ist sowohl ein EPSG-Code "EPSG:...",
- * als auch eine WKT-Definition erlaubt. Kann kein CRS ermitteln werden,
- * wird {@link #DEFAULT_CRS} als CRS verwendet.
- * @param file GeoTIFF-File
- * @param crs erzwungenes CoordinateReferenceSystem fuer das Raster (kann {@code null} sein)
- * @throws java.lang.Exception bei irgendeinem Fehler
- */
- public static WritableGridRaster readGridRasterFromGeoTiff(File file, CoordinateReferenceSystem crs) throws Exception {
-// // GeoTiff-File einlesen
-// BufferedImage im = ImageIO.read( file );
-// if ( im == null )
-// throw new IIOException("No image reader found for this image type!");
-// // World-File einlesen
-// File tfw = IOUtil.changeFileExt(file,"tfw");
-// double[] tfwInfo = readWorldFile(tfw);
-// // ggf. Projektion einlesen
-// if (crs == null)
-// crs = determineProjection(file);
-//
-// float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite = RasterSpalten * hor. Aufloesung
-// float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe = RasterZeilen * vert. Aufloesung
-// float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
-// float y = (float) tfwInfo[5] - h ; // Suedwestliche Ecke (im tfw-File steht die Nordwestliche!)
-//
-// Rectangle2D env = new Rectangle2D.Float(x,y,w,h);
-// WritableGridRaster raster = new WritableGridRaster(
-// im.getData().getDataBuffer().getDataType(),
-// 0,
-// 0,
-// im.getWidth(),
-// im.getHeight(),
-// env,
-// crs
-// );
-//
+ /**
+ * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
+ * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
+ * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
+ * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert und
+ * eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
+ * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
+ * <ol>
+ * <li>Zellengroesse in X-Richtung (in Meter)</li>
+ * <li>Koeffizient fuer Rotation in Y-Richtung</li>
+ * <li>Koeffizient fuer Rotation in X-Richtung</li>
+ * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
+ * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
+ * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
+ * </ol>
+ *
+ * @todo WorldFile-Spec vervollstaendigen
+ * @param file
+ * World-File
+ * @exception IOException
+ * falls die Datei nicht existiert oder ein unerwarteter
+ * Fehler beim Einlesen auftritt
+ * @see IOUtil#isCommentLine(String)
+ * @see System#err
+ */
- GridCoverage2D gc = readGridFromGeoTiff(file,crs);
- Rectangle2D env = gc.getEnvelope2D();
- RenderedImage im = gc.getRenderedImage();
- WritableGridRaster raster = new WritableGridRaster(
- im.getData().getDataBuffer().getDataType(),
- 0,
- 0,
- im.getWidth(),
- im.getHeight(),
- env,
- crs
- );
+ public static double[] readWorldFile(File file) throws IOException {
+ return readWorldFile(new FileInputStream(file));
+ }
- im.copyData(raster);
+ /**
+ * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
+ * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
+ * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
+ * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert und
+ * eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
+ * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
+ * <ol>
+ * <li>Zellengroesse in X-Richtung (in Meter)</li>
+ * <li>Koeffizient fuer Rotation in Y-Richtung</li>
+ * <li>Koeffizient fuer Rotation in X-Richtung</li>
+ * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
+ * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
+ * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
+ * </ol>
+ *
+ * @todo WorldFile-Spec vervollstaendigen
+ *
+ * @param inputStream
+ * Stream of World-File
+ * @exception IOException
+ * falls die Datei nicht existiert oder ein unerwarteter
+ * Fehler beim Einlesen auftritt
+ * @see IOUtil#isCommentLine(String)
+ * @see System#err
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static double[] readWorldFile(InputStream inputStream)
+ throws IOException {
+ Vector<Double> tfwValues = new Vector<Double>();
+ BufferedReader in = new BufferedReader(new InputStreamReader(
+ inputStream));
+ String line = null;
+ for (int lineNo = 1; in.ready()
+ && (line = in.readLine().trim()) != null; lineNo++) {
+ if (IOUtil.isCommentLine(line) || line.equals(""))
+ continue;
+ try {
+ StringTokenizer st = new StringTokenizer(line);
+ tfwValues.add(Double.parseDouble(st.nextToken(" \n;,#|/")));
+ } catch (Exception err) {
+ System.err.println("WorldFile-Error in line " + lineNo + ": "
+ + err);
- return raster;
- }
+ // (SK)
+ // System.err.println("WorldFile-Error in '"+file.getAbsolutePath()+"' (line "+lineNo+"): "+err);
+ System.err.println(" >> expected value is set to 1.0");
+ tfwValues.add(1.0);
+ }
+ }
- /**
- * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
- * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
- * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
- * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert
- * und eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
- * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
- * <ol>
- * <li>Zellengroesse in X-Richtung (in Meter)</li>
- * <li>Koeffizient fuer Rotation in Y-Richtung</li>
- * <li>Koeffizient fuer Rotation in X-Richtung</li>
- * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
- * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
- * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
- * </ol>
- * @todo WorldFile-Spec vervollstaendigen
- * @param file World-File
- * @exception IOException falls die Datei nicht existiert oder ein unerwarteter
- * Fehler beim Einlesen auftritt
- * @see IOUtil#isCommentLine(String)
- * @see System#err
- */
+ while (tfwValues.size() < 6) {
+ System.err.println("WorldFile-Error: value " + tfwValues.size()
+ + " missing!");
+ // (SK)
+ // System.err.println("WorldFile-Error in '"+file.getAbsolutePath()+"': value "+tfwValues.size()+" missing!");
+ System.err.println(" >> expected value is set to 1.0");
+ tfwValues.add(1.0);
+ }
- public static double[] readWorldFile(File file) throws IOException {
- return readWorldFile( new FileInputStream(file) ) ;
- }
+ // Vector in Array umwandeln
+ double[] ret = new double[tfwValues.size()];
+ for (int i = 0; i < ret.length; i++)
+ ret[i] = tfwValues.elementAt(i);
+ return ret;
+ }
+ /**
+ * Liest das CRS aus einer Datei. Zunaechst wird versucht das CRS aus der
+ * uebergebene Datei zu lesen. Ist dies nicht erfolgreich wird das zur Datei
+ * korrespondierende prj-File herangezogen.
+ *
+ * @param file
+ * Datei
+ * @return {@code null}, wenn kein CRS gelesen werden konnte
+ */
+ public static CoordinateReferenceSystem determineProjection(File file)
+ throws IOException {
- /**
- * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
- * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
- * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
- * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert
- * und eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
- * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
- * <ol>
- * <li>Zellengroesse in X-Richtung (in Meter)</li>
- * <li>Koeffizient fuer Rotation in Y-Richtung</li>
- * <li>Koeffizient fuer Rotation in X-Richtung</li>
- * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
- * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
- * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
- * </ol>
- * @todo WorldFile-Spec vervollstaendigen
- *
- * @param inputStream Stream of World-File
- * @exception IOException falls die Datei nicht existiert oder ein unerwarteter
- * Fehler beim Einlesen auftritt
- * @see IOUtil#isCommentLine(String)
- * @see System#err
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- */
- public static double[] readWorldFile(InputStream inputStream) throws IOException {
- Vector<Double> tfwValues = new Vector<Double>();
- BufferedReader in = new BufferedReader( new InputStreamReader( inputStream ) );
- String line = null;
- for(int lineNo=1; in.ready() && (line=in.readLine().trim()) != null; lineNo++ ) {
- if ( IOUtil.isCommentLine(line) || line.equals("") )
- continue;
- try {
- StringTokenizer st = new StringTokenizer(line);
- tfwValues.add( Double.parseDouble( st.nextToken(" \n;,#|/") ) );
- } catch (Exception err) {
- System.err.println("WorldFile-Error in line "+lineNo+": "+err);
+ // ****************************************************************************
+ // schonmal teilweise migriert... das geht direkt an die URL methode
+ // weiter...
+ // ****************************************************************************
-// (SK) System.err.println("WorldFile-Error in '"+file.getAbsolutePath()+"' (line "+lineNo+"): "+err);
- System.err.println(" >> expected value is set to 1.0");
- tfwValues.add( 1.0 );
- }
- }
+ // CoordinateReferenceSystem crs = null;
+ // // Versuchen CRS aus angegebener Datei zu lesen
+ // crs = readProjectionFile(file);
+ // // Wenn nicht erfolgreich versuchen die zur Datei korrespondierende
+ // // prj-Datei einzulesen
+ // if ( crs == null )
+ // crs = readProjectionFile( IOUtil.changeFileExt(file,"prj") );
+ // // Wenn nicht erfolgreich, Default verwenden
+ // if ( crs == null ) {
+ // LOGGER.warn("No projection found for file '"+file.getName()+"'. Default CRS used.");
+ // crs = DEFAULT_CRS;
+ // }
+ return determineProjection(file.toURI().toURL());
+ }
- while ( tfwValues.size() < 6 ) {
- System.err.println("WorldFile-Error: value "+tfwValues.size()+" missing!");
-// (SK) System.err.println("WorldFile-Error in '"+file.getAbsolutePath()+"': value "+tfwValues.size()+" missing!");
- System.err.println(" >> expected value is set to 1.0");
- tfwValues.add( 1.0 );
- }
-
- // Vector in Array umwandeln
- double[] ret = new double[tfwValues.size()];
- for (int i=0; i<ret.length; i++)
- ret[i] = tfwValues.elementAt(i);
- return ret;
- }
-
- /**
- * Liest das CRS aus einer Datei. Zunaechst wird versucht das CRS aus der
- * uebergebene Datei zu lesen. Ist dies nicht erfolgreich wird das zur
- * Datei korrespondierende prj-File herangezogen.
- * @param file Datei
- * @return {@code null}, wenn kein CRS gelesen werden konnte
- */
- public static CoordinateReferenceSystem determineProjection(File file) throws IOException {
-
- //****************************************************************************
- // schonmal teilweise migriert... das geht direkt an die URL methode weiter...
- //****************************************************************************
-
-// CoordinateReferenceSystem crs = null;
-// // Versuchen CRS aus angegebener Datei zu lesen
-// crs = readProjectionFile(file);
-// // Wenn nicht erfolgreich versuchen die zur Datei korrespondierende
-// // prj-Datei einzulesen
-// if ( crs == null )
-// crs = readProjectionFile( IOUtil.changeFileExt(file,"prj") );
-// // Wenn nicht erfolgreich, Default verwenden
-// if ( crs == null ) {
-// LOGGER.warn("No projection found for file '"+file.getName()+"'. Default CRS used.");
-// crs = DEFAULT_CRS;
-// }
- return determineProjection(file.toURI().toURL());
- }
-
-
/**
* Liest das CRS aus einer URL. Wenn keine CRS gelesen werden kann, dann
* wird die Endung der URL gegen .prj gewechselt und nochmal versucht bevor
@@ -766,119 +920,138 @@
return crs;
}
+ /**
+ * Liest ein CRS aus einer URL. Als Dateiinhalt wird entweder ein EPSG-Code
+ * oder eine WKT-Definition des CRS akzeptiert.
+ *
+ * @param prjURL
+ * prj-Datei in der die Projektion hinterlegt ist
+ * @return {@code null}, wenn kein CRS gelesen werden konnte
+ * @see GTUtil#createCRS(String)
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ * @throws IOException
+ * falls die URL nicht wie erwartet gelesen werden konnte.
+ */
+ public static CoordinateReferenceSystem readProjectionFile(URL prjURL)
+ throws IOException {
+ String crsDefinition = readProjectionString(prjURL);
+ CoordinateReferenceSystem crs = GTUtil.createCRS(crsDefinition);
+ return crs;
+ }
- /**
- * Liest ein CRS aus einer URL. Als Dateiinhalt wird entweder ein
- * EPSG-Code oder eine WKT-Definition des CRS akzeptiert.
- * @param prjURL prj-Datei in der die Projektion hinterlegt ist
- * @return {@code null}, wenn kein CRS gelesen werden konnte
- * @see GTUtil#createCRS(String)
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- * @throws IOException falls die URL nicht wie erwartet gelesen werden konnte.
- */
- public static CoordinateReferenceSystem readProjectionFile(URL prjURL) throws IOException {
- String crsDefinition = readProjectionString(prjURL);
- CoordinateReferenceSystem crs = GTUtil.createCRS( crsDefinition );
- return crs;
- }
+ /**
+ * Liest ein CRS aus einer Datei. Als Dateiinhalt wird entweder ein
+ * EPSG-Code oder eine WKT-Definition des CRS akzeptiert.
+ *
+ * @param prjFile
+ * prj-Datei in der die Projektion hinterlegt ist
+ * @return {@code null}, wenn kein CRS gelesen werden konnte
+ * @see GTUtil#createCRS(String)
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ */
+ public static CoordinateReferenceSystem readProjectionFile(File prjFile)
+ throws IOException {
+ String crsDefinition = readProjectionString(prjFile);
+ CoordinateReferenceSystem crs = GTUtil.createCRS(crsDefinition);
+ // if ( crs == null )
+ // LOGGER.warn("CRS can not be read from file '"+(prjFile == null ?
+ // "null" : prjFile.getName())+"'");
+ return crs;
+ }
- /**
- * Liest ein CRS aus einer Datei. Als Dateiinhalt wird entweder ein
- * EPSG-Code oder eine WKT-Definition des CRS akzeptiert.
- * @param prjFile prj-Datei in der die Projektion hinterlegt ist
- * @return {@code null}, wenn kein CRS gelesen werden konnte
- * @see GTUtil#createCRS(String)
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- */
- public static CoordinateReferenceSystem readProjectionFile(File prjFile) throws IOException {
- String crsDefinition = readProjectionString(prjFile);
- CoordinateReferenceSystem crs = GTUtil.createCRS( crsDefinition );
-// if ( crs == null )
-// LOGGER.warn("CRS can not be read from file '"+(prjFile == null ? "null" : prjFile.getName())+"'");
- return crs;
- }
+ /**
+ * Liest die ersten Zeilen der angegebenen prj-Datei und fuegt sie zu einem
+ * String zusammen. Wenn die Datei zu gross ist, wird ein Leerstring
+ * zurueckgegeben, da es sich dann nicht um eine Projektionsdefinition
+ * handelt.
+ *
+ * @param prjFile
+ * prj-Datei
+ * @return Leerstring, falls die Datei nicht existiert oder groesser als
+ * 10KB ist
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ */
+ private static String readProjectionString(File prjFile) throws IOException {
+ // Wenn Datei groesser als 10KB, dann ist es kein prj-File
+ if (!prjFile.exists() || !prjFile.isFile() || prjFile.length() == 0
+ || prjFile.length() > 10240)
+ return "";
- /**
- * Liest die ersten Zeilen der angegebenen prj-Datei und fuegt sie zu einem
- * String zusammen. Wenn die Datei zu gross ist, wird ein Leerstring zurueckgegeben,
- * da es sich dann nicht um eine Projektionsdefinition handelt.
- * @param prjFile prj-Datei
- * @return Leerstring, falls die Datei nicht existiert oder groesser als 10KB ist
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- */
- private static String readProjectionString(File prjFile) throws IOException {
- // Wenn Datei groesser als 10KB, dann ist es kein prj-File
- if ( !prjFile.exists() || !prjFile.isFile() ||
- prjFile.length() == 0 || prjFile.length() > 10240 )
- return "";
+ // Alle Zeilen der Datei aneinander haengen
+ BufferedReader input = new BufferedReader(new InputStreamReader(
+ new FileInputStream(prjFile)));
+ StringBuffer buffer = new StringBuffer();
+ String line = null;
+ while (input.ready() && (line = input.readLine()) != null)
+ if (!IOUtil.isCommentLine(line))
+ buffer.append(" ").append(line);
+ input.close();
+ return buffer.toString().trim();
- // Alle Zeilen der Datei aneinander haengen
- BufferedReader input = new BufferedReader( new InputStreamReader( new FileInputStream(prjFile) ) );
- StringBuffer buffer = new StringBuffer();
- String line = null;
- while( input.ready() && (line = input.readLine()) != null )
- if ( !IOUtil.isCommentLine(line) )
- buffer.append(" ").append(line);
- input.close();
- return buffer.toString().trim();
+ }
- }
+ /**
+ * Liest alle Zeilen aus der prj-Datei URL und fuegt diese zu einem String
+ * zusammen
+ *
+ * Kommentarzeilen werden ignoriert.
+ *
+ * Wenn mehr als 3000 Zeichen (ohne Kommentare) gelesen werden, wird davon
+ * ausgegangen, dass es sich nicht um eine .PRJ Datei handelt, und "" wird
+ * zurückgegeben.
+ *
+ * @param url
+ * {@link URL} auf prj-Datei
+ *
+ * @return Leerstring, wenn url == null
+ *
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static String readProjectionString(URL url) throws IOException {
+ if (url == null) {
+ LOGGER
+ .debug("readProjectionString returned empty String for url==null");
+ return "";
+ }
- /**
- * Liest alle Zeilen aus der prj-Datei URL und fuegt diese zu einem
- * String zusammen
- *
- * Kommentarzeilen werden ignoriert.
- *
- * Wenn mehr als 3000 Zeichen (ohne Kommentare) gelesen werden, wird davon
- * ausgegangen, dass es sich nicht um eine .PRJ Datei handelt, und "" wird
- * zurückgegeben.
- *
- * @param url {@link URL} auf prj-Datei
- *
- * @return Leerstring, wenn url == null
- *
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- */
- public static String readProjectionString(URL url) throws IOException {
- if (url == null) {
- LOGGER.debug("readProjectionString returned empty String for url==null");
- return "";
- }
+ BufferedReader input = new BufferedReader(new InputStreamReader(url
+ .openStream()));
+ try {
+ // Alle Zeilen der Datei aneinander haengen
+ StringBuffer buffer = new StringBuffer();
+ String line = null;
+ while (input.ready() && (line = input.readLine()) != null) {
+ if (!IOUtil.isCommentLine(line))
+ buffer.append(" ").append(line);
+ if (buffer.length() > 3000) {
+ // LOGGER.warn("The URL " + url +
+ // " doesn't seem point to a .prj file, because size is > 3000 characters. Returning \"\"");
+ return "";
+ }
+ }
+ final String prjString = buffer.toString().trim();
+ // LOGGER.debug("This is the PRJ String from URL = \n"+prjString);
+ return prjString;
+ } finally {
+ input.close();
+ }
+ }
- BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
- try {
- // Alle Zeilen der Datei aneinander haengen
- StringBuffer buffer = new StringBuffer();
- String line = null;
- while (input.ready() && (line = input.readLine()) != null) {
- if (!IOUtil.isCommentLine(line))
- buffer.append(" ").append(line);
- if (buffer.length() > 3000) {
-// LOGGER.warn("The URL " + url + " doesn't seem point to a .prj file, because size is > 3000 characters. Returning \"\"");
- return "";
- }
- }
- final String prjString = buffer.toString().trim();
- // LOGGER.debug("This is the PRJ String from URL = \n"+prjString);
- return prjString;
- } finally {
- input.close();
- }
- }
+ public static void setDEFAULT_CRS(CoordinateReferenceSystem dEFAULT_CRS) {
+ DEFAULT_CRS = dEFAULT_CRS;
+ }
+ public static CoordinateReferenceSystem getDEFAULT_CRS() {
+ return DEFAULT_CRS;
+ }
-public static void setDEFAULT_CRS(CoordinateReferenceSystem dEFAULT_CRS) {
- DEFAULT_CRS = dEFAULT_CRS;
}
-
-
-public static CoordinateReferenceSystem getDEFAULT_CRS() {
- return DEFAULT_CRS;
-}
-
- }
Modified: trunk/src/schmitzm/geotools/styling/StylingUtil.java
===================================================================
--- trunk/src/schmitzm/geotools/styling/StylingUtil.java 2009-08-19 18:30:50 UTC (rev 306)
+++ trunk/src/schmitzm/geotools/styling/StylingUtil.java 2009-08-20 13:49:50 UTC (rev 307)
@@ -40,7 +40,6 @@
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
-import java.io.Writer;
import java.lang.reflect.Array;
import java.net.URL;
import java.nio.charset.Charset;
Modified: trunk/src/schmitzm/io/IOUtil.java
===================================================================
--- trunk/src/schmitzm/io/IOUtil.java 2009-08-19 18:30:50 UTC (rev 306)
+++ trunk/src/schmitzm/io/IOUtil.java 2009-08-20 13:49:50 UTC (rev 307)
@@ -587,4 +587,17 @@
return tempDir;
}
+
+ /**
+ * Test whether it is possible to access the given URL.
+ */
+ public static boolean urlExists(final URL url) {
+ try {
+ url.openStream().close();
+ } catch (final IOException e) {
+ return false;
+ }
+ return true;
+ }
+
}
Modified: trunk/src/schmitzm/swing/SwingUtil.java
===================================================================
--- trunk/src/schmitzm/swing/SwingUtil.java 2009-08-19 18:30:50 UTC (rev 306)
+++ trunk/src/schmitzm/swing/SwingUtil.java 2009-08-20 13:49:50 UTC (rev 307)
@@ -65,18 +65,20 @@
import schmitzm.lang.ResourceProvider;
/**
- * Diese Klasse beinhaltet statische Hilfsfunktionen fuer das Arbeiten
- * mit Swing-GUIs.
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
+ * Diese Klasse beinhaltet statische Hilfsfunktionen fuer das Arbeiten mit
+ * Swing-GUIs.
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
* @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- *
+ *
* @version 1.1
*/
public class SwingUtil {
- private static final Logger LOGGER = Logger.getLogger( SwingUtil.class.getClass().getName() );
+ private static final Logger LOGGER = Logger.getLogger(SwingUtil.class
+ .getClass().getName());
- /**
+ /**
* {@link ResourceProvider}, der die Lokalisation fuer GUI-Komponenten des
* Package {@code schmitzm.swing} zur Verfuegung stellt. Diese sind in
* properties-Dateien unter {@code schmitzm.swing.resource.locales}
@@ -88,142 +90,177 @@
/**
* Convenience method to access the translation resources.
- */
+ */
public static String R(String key, Object... values) {
return RESOURCE.getString(key, values);
}
- //****************************************************************************
- // Diese Icons sind auf Basis der Icons von Gimp erstellt
- // Eine Sammlung aller Gimp-Icons liegt im svn: gimp-tool-cursors.xcf
- //****************************************************************************
- /** Cursor in Form einer Lupe mit Plus Symbol */
- public static final Cursor ZOOMIN_CURSOR = createCursorFromResourcePath("resource/cursor/zoom_in.gif",8,8,null);
- /** Cursor in Form einer Lupe mit Minus Symbol */
- public static final Cursor ZOOMOUT_CURSOR = createCursorFromResourcePath("resource/cursor/zoom_out.gif",8,8,null);
- /** Cursor in Form einer Lupe ohne Symbol*/
- public static final Cursor ZOOM_CURSOR = createCursorFromResourcePath("resource/cursor/zoom.gif",8,8,null);
- /** Cursor in Form einer offenen Hand **/
- public static final Cursor PAN_CURSOR = createCursorFromResourcePath("resource/cursor/hand_pan.png",9,11,null);
- /** Cursor in Form einer geschlossenen Hand **/
- public static final Cursor PANNING_CURSOR = createCursorFromResourcePath("resource/cursor/hand_closed.png",9,11,null);
- /** Cursor in Form einer geschlossenen Hand **/
- public static final Cursor CROSSHAIR_CURSOR = createCursorFromResourcePath("resource/cursor/crosshair.gif",10,10,null);
+ // ****************************************************************************
+ // Diese Icons sind auf Basis der Icons von Gimp erstellt
+ // Eine Sammlung aller Gimp-Icons liegt im svn: gimp-tool-cursors.xcf
+ // ****************************************************************************
+ /** Cursor in Form einer Lupe mit Plus Symbol */
+ public static final Cursor ZOOMIN_CURSOR = createCursorFromResourcePath(
+ "resource/cursor/zoom_in.gif", 8, 8, null);
+ /** Cursor in Form einer Lupe mit Minus Symbol */
+ public static final Cursor ZOOMOUT_CURSOR = createCursorFromResourcePath(
+ "resource/cursor/zoom_out.gif", 8, 8, null);
+ /** Cursor in Form einer Lupe ohne Symbol */
+ public static final Cursor ZOOM_CURSOR = createCursorFromResourcePath(
+ "resource/cursor/zoom.gif", 8, 8, null);
+ /** Cursor in Form einer offenen Hand **/
+ public static final Cursor PAN_CURSOR = createCursorFromResourcePath(
+ "resource/cursor/hand_pan.png", 9, 11, null);
+ /** Cursor in Form einer geschlossenen Hand **/
+ public static final Cursor PANNING_CURSOR = createCursorFromResourcePath(
+ "resource/cursor/hand_closed.png", 9, 11, null);
+ /** Cursor in Form einer geschlossenen Hand **/
+ public static final Cursor CROSSHAIR_CURSOR = createCursorFromResourcePath(
+ "resource/cursor/crosshair.gif", 10, 10, null);
-// public static final ImageIcon ICON_RASTER = createImageIconFromResourcePath("resource/icon/small/raster.png","");
-// public static final ImageIcon ICON_VECTOR = createImageIconFromResourcePath("resource/icon/small/vector.png","");
+ // public static final ImageIcon ICON_RASTER =
+ // createImageIconFromResourcePath("resource/icon/small/raster.png","");
+ // public static final ImageIcon ICON_VECTOR =
+ // createImageIconFromResourcePath("resource/icon/small/vector.png","");
+ /**
+ * Modus "Innen".
+ *
+ * @see #setRelativeFramePosition(Window,Window,int,int)
+ */
+ public static final int BOUNDS_INNER = 10;
+ /**
+ * Modus "Aussen".
+ *
+ * @see #setRelativeFramePosition(Window,Window,int,int)
+ */
+ public static final int BOUNDS_OUTER = 20;
+ /** Ausrichtung oben-mitte. */
+ public static final int NORTH = GridBagConstraints.NORTH;
+ /** Ausrichtung oben-links. */
+ public static final int NORTHWEST = GridBagConstraints.NORTHWEST;
+ /** Ausrichtung oben-rechts. */
+ public static final int NORTHEAST = GridBagConstraints.NORTHEAST;
+ /** Ausrichtung unten-mitte. */
+ public static final int SOUTH = GridBagConstraints.SOUTH;
+ /** Ausrichtung unten-links. */
+ public static final int SOUTHWEST = GridBagConstraints.SOUTHWEST;
+ /** Ausrichtung unten-rechts. */
+ public static final int SOUTHEAST = GridBagConstraints.SOUTHEAST;
+ /** Ausrichtung zentriert. */
+ public static final int CENTER = GridBagConstraints.CENTER;
+ /** Ausrichtung mitte-links. */
+ public static final int WEST = GridBagConstraints.WEST;
+ /** Ausrichtung mitte-rechts. */
+ public static final int EAST = GridBagConstraints.EAST;
- /** Modus "Innen".
- * @see #setRelativeFramePosition(Window,Window,int,int) */
- public static final int BOUNDS_INNER = 10;
- /** Modus "Aussen".
- * @see #setRelativeFramePosition(Window,Window,int,int) */
- public static final int BOUNDS_OUTER = 20;
- /** Ausrichtung oben-mitte. */
- public static final int NORTH = GridBagConstraints.NORTH;
- /** Ausrichtung oben-links. */
- public static final int NORTHWEST = GridBagConstraints.NORTHWEST;
- /** Ausrichtung oben-rechts. */
- public static final int NORTHEAST = GridBagConstraints.NORTHEAST;
- /** Ausrichtung unten-mitte. */
- public static final int SOUTH = GridBagConstraints.SOUTH;
- /** Ausrichtung unten-links. */
- public static final int SOUTHWEST = GridBagConstraints.SOUTHWEST;
- /** Ausrichtung unten-rechts. */
- public static final int SOUTHEAST = GridBagConstraints.SOUTHEAST;
- /** Ausrichtung zentriert. */
- public static final int CENTER = GridBagConstraints.CENTER;
- /** Ausrichtung mitte-links. */
- public static final int WEST = GridBagConstraints.WEST;
- /** Ausrichtung mitte-rechts. */
- public static final int EAST = GridBagConstraints.EAST;
+ /**
+ * Erzeugt ein Icon auf Basis einer relativen Pfad-Angabe. Als
+ * Basis-Verzeichnis wird der Classpath von {@code SwingUtil} verwendet.
+ *
+ * @param imgPath
+ * relativer Pfad des Icons
+ * @param imgDesc
+ * Beschreibung fuer Icon
+ * @return {@code null}, wenn das Icon nicht gefunden wird
+ */
+ public static ImageIcon createImageIconFromResourcePath(String imgPath,
+ String imgDesc) {
+ return createImageIconFromResourcePath(null, imgPath, imgDesc);
+ }
- /**
- * Erzeugt ein Icon auf Basis einer relativen Pfad-Angabe. Als Basis-Verzeichnis
- * wird der Classpath von {@code SwingUtil} verwendet.
- * @param imgPath relativer Pfad des Icons
- * @param imgDesc Beschreibung fuer Icon
- * @return {@code null}, wenn das Icon nicht gefunden wird
- */
- public static ImageIcon createImageIconFromResourcePath(String imgPath, String imgDesc) {
- return createImageIconFromResourcePath(null,imgPath,imgDesc);
- }
+ /**
+ * Erzeugt ein Icon auf Basis einer relativen Pfad-Angabe.
+ *
+ * @param resourceBase
+ * Klasse, deren Classpath als Basis-Verzeichnis verwendet wird
+ * @param imgPath
+ * relativer Pfad des Icons
+ * @param imgDesc
+ * Beschreibung fuer Icon
+ * @return {@code null}, wenn das Icon nicht gefunden wird
+ */
+ public static ImageIcon createImageIconFromResourcePath(Class resourceBase,
+ String imgPath, String imgDesc) {
+ if (resourceBase == null)
+ resourceBase = SwingUtil.class;
+ java.net.URL imgURL = resourceBase.getResource(imgPath);
+ if (imgURL == null) {
+ LOGGER.error("Couldn't find image file: " + imgPath);
+ return null;
+ }
+ return new ImageIcon(imgURL, imgDesc);
+ }
- /**
- * Erzeugt ein Icon auf Basis einer relativen Pfad-Angabe.
- * @param resourceBase Klasse, deren Classpath als Basis-Verzeichnis verwendet wird
- * @param imgPath relativer Pfad des Icons
- * @param imgDesc Beschreibung fuer Icon
- * @return {@code null}, wenn das Icon nicht gefunden wird
- */
- public static ImageIcon createImageIconFromResourcePath(Class resourceBase, String imgPath, String imgDesc) {
- if ( resourceBase == null )
- resourceBase = SwingUtil.class;
- java.net.URL imgURL = resourceBase.getResource(imgPath);
- if (imgURL == null) {
- LOGGER.error("Couldn't find image file: " + imgPath);
- return null;
- }
- return new ImageIcon(imgURL, imgDesc);
- }
+ /**
+ * Erzeugt einen {@link Cursor} auf Basis einer relativen Pfad-Angabe. Als
+ * Basis-Verzeichnis wird der Classpath von {@code SwingUtil} verwendet.
+ *
+ * @param imgPath
+ * relativer Pfad des Icons
+ * @param x
+ * X-Position im Image, die den Hotspot des Cursors darstellen
+ * soll
+ * @param y
+ * Y-Position im Image, die den Hotspot des Cursors darstellen
+ * soll
+ * @param name
+ * Bezeichnung fuer den Cursor
+ * @return {@code null}, wenn das Icon nicht gefunden wird
+ */
+ public static Cursor createCursorFromResourcePath(String imgPath, int x,
+ int y, String name) {
+ java.net.URL imgURL = SwingUtil.class.getResource(imgPath);
+ try {
+ return Toolkit.getDefaultToolkit().createCustomCursor(
+ ImageIO.read(imgURL), new Point(x, y), name);
+ } catch (Exception err) {
+ return null;
+ }
+ }
- /**
- * Erzeugt einen {@link Cursor} auf Basis einer relativen Pfad-Angabe.
- * Als Basis-Verzeichnis wird der Classpath von {@code SwingUtil} verwendet.
- * @param imgPath relativer Pfad des Icons
- * @param x X-Position im Image, die den Hotspot des Cursors darstellen soll
- * @param y Y-Position im Image, die den Hotspot des Cursors darstellen soll
- * @param name Bezeichnung fuer den Cursor
- * @return {@code null}, wenn das Icon nicht gefunden wird
- */
- public static Cursor createCursorFromResourcePath(String imgPath, int x, int y, String name) {
- java.net.URL imgURL = SwingUtil.class.getResource(imgPath);
- try {
- return Toolkit.getDefaultToolkit().createCustomCursor(
- ImageIO.read(imgURL),
- new Point(x, y),
- name
- );
- } catch( Exception err ) {
- return null;
- }
- }
+ /**
+ * Erzeugt ein neues Fenster mit {@link BorderLayout} und zeigt darin eine
+ * {@link Component} an.
+ *
+ * @param comp
+ * anzuzeigende Komponente (kann {@code null} sein)
+ * @param title
+ * Titel des Fensters (kann {@code null} sein)
+ * @param icon
+ * Icon-Image (kann {@code null} sein)
+ */
+ public static JFrame createFrame(Component comp, String title, Image icon) {
+ JFrame frame = new JFrame(title);
+ frame.getContentPane().setLayout(new BorderLayout());
+ if (comp != null)
+ frame.getContentPane().add(comp, BorderLayout.CENTER);
+ if (title != null)
+ frame.setTitle(title);
+ if (icon != null)
+ frame.setIconImage(icon);
+ frame.pack();
+ return frame;
+ }
- /**
- * Erzeugt ein neues Fenster mit {@link BorderLayout} und zeigt darin
- * eine {@link Component} an.
- * @param comp anzuzeigende Komponente (kann {@code null} sein)
- * @param title Titel des Fensters (kann {@code null} sein)
- * @param icon Icon-Image (kann {@code null} sein)
- */
- public static JFrame createFrame(Component comp, String title, Image icon) {
- JFrame frame = new JFrame( title );
- frame.getContentPane().setLayout( new BorderLayout() );
- if ( comp != null )
- frame.getContentPane().add( comp, BorderLayout.CENTER );
- if ( title != null )
- frame.setTitle( title );
- if ( icon != null )
- frame.setIconImage( icon );
- frame.pack();
- return frame;
- }
+ /**
+ * Zeigt ein neues Fenster einer {@link Component} an.
+ *
+ * @param comp
+ * anzuzeigende Komponente (kann {@code null} sein)
+ * @param title
+ * Titel des Fensters (kann {@code null} sein)
+ * @param icon
+ * Icon-Image (kann {@code null} sein)
+ * @see #createFrame(Component, String, Image)
+ */
+ public static JFrame showFrame(Component comp, String title, Image icon) {
+ JFrame frame = createFrame(comp, title, icon);
+ frame.setVisible(true);
+ return frame;
+ }
- /**
- * Zeigt ein neues Fenster einer {@link Component} an.
- * @param comp anzuzeigende Komponente (kann {@code null} sein)
- * @param title Titel des Fensters (kann {@code null} sein)
- * @param icon Icon-Image (kann {@code null} sein)
- * @see #createFrame(Component, String, Image)
- */
- public static JFrame showFrame(Component comp, String title, Image icon) {
- JFrame frame = createFrame(comp,title,icon);
- frame.setVisible( true );
- return frame;
- }
-
- /**
+ /**
* Liefert das Fenster, das eine GUI-Komponente beinhaltet. Wenn
* GUI-Komponente selber ein {@link Window} ist, wird diese zurückgelifert.
*
@@ -242,567 +279,750 @@
return (Window) comp;
}
- /**
- * Liefert den {@link Frame}, das eine Kompoenente beinhaltet.
- * @param comp eine GUI-Komponente
- * @return <code>null</code> falls die Komponente in keinem {@link Frame}
- * enthalten ist
- */
- public static Frame getParentFrame(Component comp) {
- // durch die Parents laufen, bis Frame gefunden
- while ( comp!=null && !(comp instanceof Frame) )
- comp = comp.getParent();
- // wenn kein Frame gefunden -> null zurueckgeben
- if ( comp== null )
- return null;
- return (Frame)comp;
- }
+ /**
+ * Liefert den {@link Frame}, das eine Kompoenente beinhaltet.
+ *
+ * @param comp
+ * eine GUI-Komponente
+ * @return <code>null</code> falls die Komponente in keinem {@link Frame}
+ * enthalten ist
+ */
+ public static Frame getParentFrame(Component comp) {
+ // durch die Parents laufen, bis Frame gefunden
+ while (comp != null && !(comp instanceof Frame))
+ comp = comp.getParent();
+ // wenn kein Frame gefunden -> null zurueckgeben
+ if (comp == null)
+ return null;
+ return (Frame) comp;
+ }
- /**
- * Liefert das Fenster, das eine Kompoenente beinhaltet. Dabei kann es sich
- * auch um einen {@link JInternalFrame} handelt.
- * @param comp eine GUI-Komponente
- * @return <code>null</code> falls die Komponente in keinem Fenster
- * enthalten ist
- */
- public static Component getParentWindowComponent(Component comp) {
- // durch die Parents laufen, bis Window gefunden
- while ( comp!=null && !(comp instanceof Window) && !(comp instanceof JInternalFrame))
- comp = comp.getParent();
- // wenn kein Window gefunden -> null zurueckgeben
- if ( comp== null )
- return null;
- return comp;
- }
+ /**
+ * Liefert das Fenster, das eine Kompoenente beinhaltet. Dabei kann es sich
+ * auch um einen {@link JInternalFrame} handelt.
+ *
+ * @param comp
+ * eine GUI-Komponente
+ * @return <code>null</code> falls die Komponente in keinem Fenster
+ * enthalten ist
+ */
+ public static Component getParentWindowComponent(Component comp) {
+ // durch die Parents laufen, bis Window gefunden
+ while (comp != null && !(comp instanceof Window)
+ && !(comp instanceof JInternalFrame))
+ comp = comp.getParent();
+ // wenn kein Window gefunden -> null zurueckgeben
+ if (comp == null)
+ return null;
+ return comp;
+ }
- /**
- * Packt das Fenster, in dem eine Kompoenente plaziert ist.
- * @param comp eine GUI-Komponente
- * @return <code>false</code> falls die Komponente in keinem Fenster
- * enthalten ist
- * @see Window#pack()
- */
- public static boolean packParentWindow(Component comp) {
- Window w = getParentWindow(comp);
- if ( w == null )
- return false;
- w.pack();
- return true;
- }
+ /**
+ * Packt das Fenster, in dem eine Kompoenente plaziert ist.
+ *
+ * @param comp
+ * eine GUI-Komponente
+ * @return <code>false</code> falls die Komponente in keinem Fenster
+ * enthalten ist
+ * @see Window#pack()
+ */
+ public static boolean packParentWindow(Component comp) {
+ Window w = getParentWindow(comp);
+ if (w == null)
+ return false;
+ w.pack();
+ return true;
+ }
- /**
- * Prueft, ob eine Komponente eine Kind-Komponente einer anderen Komponente ist.
- * @param child Component
- * @param parent Component
- * @return {@code false} wenn {@code child == null}, {@code true} wenn {@code child == parent},
- * {@code isChildComponent(child.getParent(),parent)} sonst
- */
- public static boolean isChildComponent(Component child, Component parent) {
- if ( child == null )
- return false;
- if ( child == parent )
- return true;
- return isChildComponent(child.getParent(),parent);
- }
+ /**
+ * Prueft, ob eine Komponente eine Kind-Komponente einer anderen Komponente
+ * ist.
+ *
+ * @param child
+ * Component
+ * @param parent
+ * Component
+ * @return {@code false} wenn {@code child == null}, {@code true} wenn
+ * {@code child == parent}, {@code
+ * isChildComponent(child.getParent(),parent)} sonst
+ */
+ public static boolean isChildComponent(Component child, Component parent) {
+ if (child == null)
+ return false;
+ if (child == parent)
+ return true;
+ return isChildComponent(child.getParent(), parent);
+ }
- /**
- * Zentriert ein Fenster auf dem Monitor.
- * @param window das zu zentrierende Fenster
- */
- public static void centerFrameOnScreen(Component comp) {
- setRelativeFramePosition(comp,0.5,0.5);
- }
+ /**
+ * Zentriert ein Fenster auf dem Monitor.
+ *
+ * @param window
+ * das zu zentrierende Fenster
+ */
+ public static void centerFrameOnScreen(Component comp) {
+ setRelativeFramePosition(comp, 0.5, 0.5);
+ }
- /**
- * Zentriert ein Fenster auf dem Monitor.<br>
- * <b>Bemerkung:</b> Da {@link Window} eine {@link Component} ist, ist diese
- * Methode eigentlich ueberfluessig. Es koennte {@link #centerFrameOnScreen(Component)}
- * verwendet werden. Merkwuerdigerweise macht XULU beim Starten von der Console
- * aus aber Probleme, wenn die Methode {@code centerFrameOnScreen(Window)} fehlt!!
- * TODO: Probleme beim Xulu-Start loesen.
- * @param window das zu zentrierende Fenster
- */
- public static void centerFrameOnScreen(Window comp) {
- setRelativeFramePosition(comp,0.5,0.5);
- }
+ /**
+ * Zentriert ein Fenster auf dem Monitor.<br>
+ * <b>Bemerkung:</b> Da {@link Window} eine {@link Component} ist, ist diese
+ * Methode eigentlich ueberfluessig. Es koennte
+ * {@link #centerFrameOnScreen(Component)} verwendet werden.
+ * Merkwuerdigerweise macht XULU beim Starten von der Console aus aber
+ * Probleme, wenn die Methode {@code centerFrameOnScreen(Window)} fehlt!!
+ * TODO: Probleme beim Xulu-Start loesen.
+ *
+ * @param window
+ * das zu zentrierende Fenster
+ */
+ public static void centerFrameOnScreen(Window comp) {
+ setRelativeFramePosition(comp, 0.5, 0.5);
+ }
- /**
- * Zentriert ein Fenster auf dem Monitor, aber verrückt das Window per Zufall um 10 Prozenz
- *
- * @param comp Eine Componente des zu zentrierenden Fensters. Wenn comp kein {@link Window} ist, wird das Parent {@link Window} ermittelt.
- *
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- */
- public static void centerFrameOnScreenRandom(Component comp) {
- Random r = new Random();
- setRelativeFramePosition(comp,0.5 + (r.nextDouble()*0.2-0.1) , 0.5 + (r.nextDouble()*0.2-0.1));
- }
+ /**
+ * Zentriert ein Fenster auf dem Monitor, aber verrückt das Window per
+ * Zufall um 10 Prozenz
+ *
+ * @param comp
+ * Eine Componente des zu zentrierenden Fensters. Wenn comp kein
+ * {@link Window} ist, wird das Parent {@link Window} ermittelt.
+ *
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static void centerFrameOnScreenRandom(Component comp) {
+ Random r = new Random();
+ setRelativeFramePosition(comp, 0.5 + (r.nextDouble() * 0.2 - 0.1),
+ 0.5 + (r.nextDouble() * 0.2 - 0.1));
+ }
+ /**
+ * Positioniert ein Fenster auf dem Monitor, relativ zu dessen Groesse.
+ * (0.5/0.5) positioniert das Fenster z.B. genau in der Mitte des Monitors;
+ * (0.25/0.5) setzt das Fenster vertikal in die Mitte und horizontal auf ein
+ * Viertel der Monitorbreite.
+ *
+ * @param comp
+ * Eine Komponente des zu positionierenden Fensters oder direckt
+ * das {@link Window}.
+ * @param relX
+ * Relationsfaktor fuer die horizontale Position (0 <
+ * <code>relX</code> < 1)
+ * @param relY
+ * Relationsfaktor fuer die vertikale Position (0 <
+ * <code>relX</code> < 1)
+ */
+ public static void setRelativeFramePosition(Component comp, double relX,
+ double relY) {
- /**
- * Positioniert ein Fenster auf dem Monitor, relativ zu dessen Groesse. (0.5/0.5)
- * positioniert das Fenster z.B. genau in der Mitte des Monitors; (0.25/0.5)
- * setzt das Fenster vertikal in die Mitte und horizontal auf ein Viertel der
- * Monitorbreite.
- * @param comp Eine Komponente des zu positionierenden Fensters oder direckt das {@link Window}.
- * @param relX Relationsfaktor fuer die horizontale Position (0 < <code>relX</code> < 1)
- * @param relY Relationsfaktor fuer die vertikale Position (0 < <code>relX</code> < 1)
- */
- public static void setRelativeFramePosition(Component comp, double relX, double relY) {
-
- setRelativeFramePosition(comp,null,relX,relY);
- }
+ setRelativeFramePosition(comp, null, relX, relY);
+ }
- /**
- * Positioniert ein Fenster auf dem Monitor relativ zur Position eines
- * anderen Fensters. (0.5/0.5) positioniert das Fenster z.B. genau in der Mitte
- * anderen Fensters. (0.25/0.5) setzt das Fenster vertikal in die Mitte und
- * horizontal auf ein Viertel des Referenz-Fensters.
- * @param comp Eine Komponente des zu positionierenden Fensters oder direkt das {@link Window}.
- * @param relFrame Fenster zu dem das Fenster in Relation gesetzt wird (wenn
- * <code>null</code> wird der gesamte Monitor verwendet)
- * @param relX Relationsfaktor fuer die horizontale Position (0 < <code>relX</code> < 1)
- * @param relY Relationsfaktor fuer die vertikale Position (0 < <code>relY</code> < 1)
- */
- public static void setRelativeFramePosition(Component comp, Window relFrame, double relX, double relY) {
-
- // Added by SK, 17.4.2009
- // sk.sc
- Window window;
- if (comp instanceof Window){
- window = (Window) comp;
- } else {
- window = SwingUtil.getParentWindow(comp);
- }
- // sk.ec
-
- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- Dimension relSize = (relFrame==null) ? screenSize : relFrame.getSize();
- Point relLocation = (relFrame==null) ? new Point(0,0) : relFrame.getLocation();
+ /**
+ * Positioniert ein Fenster auf dem Monitor relativ zur Position eines
+ * anderen Fensters. (0.5/0.5) positioniert das Fenster z.B. genau in der
+ * Mitte anderen Fensters. (0.25/0.5) setzt das Fenster vertikal in die
+ * Mitte und horizontal auf ein Viertel des Referenz-Fensters.
+ *
+ * @param comp
+ * Eine Komponente des zu positionierenden Fensters oder direkt
+ * das {@link Window}.
+ * @param relFrame
+ * Fenster zu dem das Fenster in Relation gesetzt wird (wenn
+ * <code>null</code> wird der gesamte Monitor verwendet)
+ * @param relX
+ * Relationsfaktor fuer die horizontale Position (0 <
+ * <code>relX</code> < 1)
+ * @param relY
+ * Relationsfaktor fuer die vertikale Position (0 <
+ * <code>relY</code> < 1)
+ */
+ public static void setRelativeFramePosition(Component comp,
+ Window relFrame, double relX, double relY) {
- // Fenster auf Monitor-Groesse anpassen
- Dimension frameSize = window.getSize();
- if (frameSize.height > screenSize.height) {
- frameSize.height = screenSize.height;
- }
- if (frameSize.width > screenSize.width) {
- frameSize.width = screenSize.width;
- }
- // Fenster positionieren
- window.setLocation( relLocation.x + Math.round( (relSize.width-frameSize.width)*(float)relX ),
- relLocation.y + Math.round( (relSize.height-frameSize.height)*(float)relY )
- );
- }
+ // Added by SK, 17.4.2009
+ // sk.sc
+ Window window;
+ if (comp instanceof Window) {
+ window = (Window) comp;
+ } else {
+ window = SwingUtil.getParentWindow(comp);
+ }
+ // sk.ec
- /**
- * Positioniert ein Fenster auf dem Monitor relativ zur Position eines
- * anderen Fensters. Das Fenster wird jedoch immer innerhalb des Bildschirms
- * positioniert.
- * @param window das zu positionierende Fenster
- * @param relWindow Fenster zu dem das Fenster in Relation gesetzt wird (wenn
- * <code>null</code> wird der gesamte Monitor verwendet)
- * @param type bestimmt, ob das Fenster innerhalb oder ausserhalb des relativen
- * Fensters positioniert wird ({@link #BOUNDS_INNER} oder {@link #BOUNDS_OUTER}).
- * @param position Positionierung des Fensters ({@link #NORTH}, {@link #NORTHEAST}, ...)
- */
- public static void setRelativeFramePosition(Window window, Window relWindow, int type, int position) {
- if ( type == BOUNDS_INNER ) {
- // An den inneren Grenzen des Frames ausrichten
- double relX = 0;
- double relY = 0;
- switch ( position ) {
- case NORTH: relX = 0.5; relY = 0.0; break;
- case NORTHWEST: relX = 0.0; relY = 0.0; break;
- case NORTHEAST: relX = 1.0; relY = 0.0; break;
- case SOUTH: relX = 0.5; relY = 1.0; break;
- case SOUTHWEST: relX = 0.0; relY = 1.0; break;
- case SOUTHEAST: relX = 1.0; relY = 1.0; break;
- case CENTER: relX = 0.5; relY = 0.5; break;
- case WEST: relX = 0.0; relY = 0.5; break;
- case EAST: relX = 1.0; relY = 0.5; break;
- default: throw new IllegalArgumentException("Unsupported mode for 'position'.");
- }
- setRelativeFramePosition(window,relWindow,relX,relY);
- return;
- }
- if ( type == BOUNDS_OUTER ) {
- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- Dimension relSize = (relWindow==null) ? screenSize : relWindow.getSize();
- Point relLocation = (relWindow==null) ? new Point(0,0) : relWindow.getLocation();
- // An den Aussen-Grenzen des Frames ausrichten
- Point loc = new Point(0,0);
- switch ( position ) {
- case NORTH:
- case NORTHWEST:
- case NORTHEAST: loc.y = relLocation.y - window.getHeight(); break;
- case SOUTH:
- case SOUTHWEST:
- case SOUTHEAST: loc.y = relLocation.y + relSize.height; break;
- case CENTER:
- case WEST:
- case EAST: loc.y = relLocation.y + relSize.height/2 - window.getHeight()/2; break;
- default: throw new IllegalArgumentException("Unsupported mode for 'position'.");
- }
- switch ( position ) {
- case WEST:
- case NORTHWEST:
- case SOUTHWEST: loc.x = relLocation.x - window.getWidth(); break;
- case EAST:
- case NORTHEAST:
- case SOUTHEAST: loc.x = relLocation.x + relSize.width; break;
- case CENTER:
- case NORTH:
- case SOUTH: loc.x = relLocation.x + relSize.width/2 - window.getWidth()/2; break;
- default: throw new IllegalArgumentException("Unsupported mode for 'position'. GridBagConstraints location expected!");
- }
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ Dimension relSize = (relFrame == null) ? screenSize : relFrame
+ .getSize();
+ Point relLocation = (relFrame == null) ? new Point(0, 0) : relFrame
+ .getLocation();
- loc.x = Math.max(0,loc.x);
- loc.y = Math.max(0,loc.y);
- if ( loc.x + window.getWidth() > screenSize.width )
- loc.x = screenSize.width - window.getWidth();
- if ( loc.y + window.getHeight() > screenSize.height )
- loc.y = screenSize.height - window.getHeight();
+ // Fenster auf Monitor-Groesse anpassen
+ Dimension frameSize = window.getSize();
+ if (frameSize.height > screenSize.height) {
+ frameSize.height = screenSize.height;
+ }
+ if (frameSize.width > screenSize.width) {
+ frameSize.width = screenSize.width;
+ }
+ // Fenster positionieren
+ window.setLocation(relLocation.x
+ + Math.round((relSize.width - frameSize.width) * (float) relX),
+ relLocation.y
+ + Math.round((relSize.height - frameSize.height)
+ * (float) relY));
+ }
- // Fenster positionieren
- window.setLocation( loc );
- return;
- }
- throw new IllegalArgumentException("Unsupported mode for 'type'. BOUNDS_INNER or BOUNDS_OUTER expected!");
- }
+ /**
+ * Positioniert ein Fenster auf dem Monitor relativ zur Position eines
+ * anderen Fensters. Das Fenster wird jedoch immer innerhalb des Bildschirms
+ * positioniert.
+ *
+ * @param window
+ * das zu positionierende Fenster
+ * @param relWindow
+ * Fenster zu dem das Fenster in Relation gesetzt wird (wenn
+ * <code>null</code> wird der gesamte Monitor verwendet)
+ * @param type
+ * bestimmt, ob das Fenster innerhalb oder ausserhalb des
+ * relativen Fensters positioniert wird ({@link #BOUNDS_INNER}
+ * oder {@link #BOUNDS_OUTER}).
+ * @param position
+ * Positionierung des Fensters ({@link #NORTH},
+ * {@link #NORTHEAST}, ...)
+ */
+ public static void setRelativeFramePosition(Window window,
+ Window relWindow, int type, int position) {
+ if (type == BOUNDS_INNER) {
+ // An den inneren Grenzen des Frames ausrichten
+ double relX = 0;
+ double relY = 0;
+ switch (position) {
+ case NORTH:
+ relX = 0.5;
+ relY = 0.0;
+ break;
+ case NORTHWEST:
+ relX = 0.0;
+ relY = 0.0;
+ break;
+ case NORTHEAST:
+ relX = 1.0;
+ relY = 0.0;
+ break;
+ case SOUTH:
+ relX = 0.5;
+ relY = 1.0;
+ break;
+ case SOUTHWEST:
+ relX = 0.0;
+ relY = 1.0;
+ break;
+ case SOUTHEAST:
+ relX = 1.0;
+ relY = 1.0;
+ break;
+ case CENTER:
+ relX = 0.5;
+ relY = 0.5;
+ break;
+ case WEST:
+ relX = 0.0;
+ relY = 0.5;
+ break;
+ case EAST:
+ relX = 1.0;
+ relY = 0.5;
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported mode for 'position'.");
+ }
+ setRelativeFramePosition(window, relWindow, relX, relY);
+ return;
+ }
+ if (type == BOUNDS_OUTER) {
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ Dimension relSize = (relWindow == null) ? screenSize : relWindow
+ .getSize();
+ Point relLocation = (relWindow == null) ? new Point(0, 0)
+ : relWindow.getLocation();
+ // An den Aussen-Grenzen des Frames ausrichten
+ Point loc = new Point(0, 0);
+ switch (position) {
+ case NORTH:
+ case NORTHWEST:
+ case NORTHEAST:
+ loc.y = relLocation.y - window.getHeight();
+ break;
+ case SOUTH:
+ case SOUTHWEST:
+ case SOUTHEAST:
+ loc.y = relLocation.y + relSize.height;
+ break;
+ case CENTER:
+ case WEST:
+ case EAST:
+ loc.y = relLocation.y + relSize.height / 2 - window.getHeight()
+ / 2;
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported mode for 'position'.");
+ }
+ switch (position) {
+ case WEST:
+ case NORTHWEST:
+ case SOUTHWEST:
+ loc.x = relLocation.x - window.getWidth();
+ break;
+ case EAST:
+ case NORTHEAST:
+ case SOUTHEAST:
+ loc.x = relLocation.x + relSize.width;
+ break;
+ case CENTER:
+ case NORTH:
+ case SOUTH:
+ loc.x = relLocation.x + relSize.width / 2 - window.getWidth()
+ / 2;
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported mode for 'position'. GridBagConstraints location expected!");
+ }
- /**
- * Aendert die Breite einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param w Breite
- */
- public static void setWidth(Component comp, int w) {
- Dimension d = comp.getPreferredSize();
- d.width = w;
- comp.setSize(d);
- }
+ loc.x = Math.max(0, loc.x);
+ loc.y = Math.max(0, loc.y);
+ if (loc.x + window.getWidth() > screenSize.width)
+ loc.x = screenSize.width - window.getWidth();
+ if (loc.y + window.getHeight() > screenSize.height)
+ loc.y = screenSize.height - window.getHeight();
- /**
- * Aendert die Hoehe einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param h Hoehe
- */
- public static void setHeight(Component comp, int h) {
- Dimension d = comp.getPreferredSize();
- d.height = h;
- comp.setSize(d);
- }
+ // Fenster positionieren
+ window.setLocation(loc);
+ return;
+ }
+ throw new IllegalArgumentException(
+ "Unsupported mode for 'type'. BOUNDS_INNER or BOUNDS_OUTER expected!");
+ }
- /**
- * Aendert die bevorzugte Breite einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param w Breite
- */
- public static void setPreferredWidth(Component comp, int w) {
- Dimension d = comp.getPreferredSize();
- d.width = w;
- comp.setPreferredSize(d);
- }
+ /**
+ * Aendert die Breite einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param w
+ * Breite
+ */
+ public static void setWidth(Component comp, int w) {
+ Dimension d = comp.getPreferredSize();
+ d.width = w;
+ comp.setSize(d);
+ }
- /**
- * Aendert die bevorzugte Hoehe einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param h Hoehe
- */
- public static void setPreferredHeight(Component comp, int h) {
- Dimension d = comp.getPreferredSize();
- d.height = h;
- comp.setPreferredSize(d);
- }
+ /**
+ * Aendert die Hoehe einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param h
+ * Hoehe
+ */
+ public static void setHeight(Component comp, int h) {
+ Dimension d = comp.getPreferredSize();
+ d.height = h;
+ comp.setSize(d);
+ }
- /**
- * Aendert die minimal erlaubte Breite einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param w Breite
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- */
- public static void setMinimumWidth(Component comp, int w) {
- Dimension d = comp.getMinimumSize();
- d.width = w;
- comp.setMinimumSize(d);
- }
+ /**
+ * Aendert die bevorzugte Breite einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param w
+ * Breite
+ */
+ public static void setPreferredWidth(Component comp, int w) {
+ Dimension d = comp.getPreferredSize();
+ d.width = w;
+ comp.setPreferredSize(d);
+ }
- /**
- * Aendert die minimal erlaubte Hoehe einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param h Hoehe
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- */
- public static void setMinimumHeight(Component comp, int h) {
- Dimension d = comp.getMinimumSize();
- d.height = h;
- comp.setMinimumSize(d);
- }
+ /**
+ * Aendert die bevorzugte Hoehe einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param h
+ * Hoehe
+ */
+ public static void setPreferredHeight(Component comp, int h) {
+ Dimension d = comp.getPreferredSize();
+ d.height = h;
+ comp.setPreferredSize(d);
+ }
- /**
- * Aendert die maximal erlaubte Breite einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param w Breite
- */
- public static void setMaximumWidth(Component comp, int w) {
- Dimension d = comp.getMaximumSize();
- d.width = w;
- comp.setMaximumSize(d);
- }
+ /**
+ * Aendert die minimal erlaubte Breite einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param w
+ * Breite
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static void setMinimumWidth(Component comp, int w) {
+ Dimension d = comp.getMinimumSize();
+ d.width = w;
+ comp.setMinimumSize(d);
+ }
- /**
- * Aendert die maximal erlaubte Hoehe einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param h Hoehe
- */
- public static void setMaximumHeight(Component comp, int h) {
- Dimension d = comp.getMaximumSize();
- d.height = h;
- comp.setMaximumSize(d);
- }
+ /**
+ * Aendert die minimal erlaubte Hoehe einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param h
+ * Hoehe
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static void setMinimumHeight(Component comp, int h) {
+ Dimension d = comp.getMinimumSize();
+ d.height = h;
+ comp.setMinimumSize(d);
+ }
- /**
- * Fixiert die Groesse einer GUI-Komponente.
- * @param comp GUI-Komponente
- * @param d Ausmasse (Hoehe und Breite)
- */
- public static void fixComponentSize(Component comp, Dimension d) {
- comp.setPreferredSize(d);
- comp.setMinimumSize(d);
- comp.setMaximumSize(d);
- }
+ /**
+ * Aendert die maximal erlaubte Breite einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param w
+ * Breite
+ */
+ public static void setMaximumWidth(Component comp, int w) {
+ Dimension d = comp.getMaximumSize();
+ d.width = w;
+ comp.setMaximumSize(d);
+ }
- /**
- * Fixiert die Groesse einer GUI-Komponente mit der aktuell
- * bevorzugten Groesse.
- * @param comp GUI-Komponente
- */
- public static void fixComponentSize(Component comp) {
- fixComponentSize(comp, comp.getPreferredSize());
- }
+ /**
+ * Aendert die maximal erlaubte Hoehe einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param h
+ * Hoehe
+ */
+ public static void setMaximumHeight(Component comp, int h) {
+ Dimension d = comp.getMaximumSize();
+ d.height = h;
+ comp.setMaximumSize(d);
+ }
- /***
- * Setzt die Hintergrundfarbe einer Komponente und aller darin enthaltener
- * Komponenten.
- * @param comp Komponente
- * @param color neue Hintergrund-Farbe
- */
- public static void setAllBackground(Component comp, Color color) {
- comp.setBackground( color );
- if ( comp instanceof JFrame )
- setAllBackground( ((JFrame)comp).getContentPane(), color );
- if ( comp instanceof JScrollPane )
- setAllBackground( ((JScrollPane)comp).getViewport(), color );
- else if ( comp instanceof Container )
- for ( Component innerComp : ((Container)comp).getComponents() )
- setAllBackground( innerComp, color );
- }
+ /**
+ * Fixiert die Groesse einer GUI-Komponente.
+ *
+ * @param comp
+ * GUI-Komponente
+ * @param d
+ * Ausmasse (Hoehe und Breite)
+ */
+ public static void fixComponentSize(Component comp, Dimension d) {
+ comp.setPreferredSize(d);
+ comp.setMinimumSize(d);
+ comp.setMaximumSize(d);
+ }
- /**
- * Versucht, aus einem String eine Farbe zu erstellen. Drei Moeglichekeiten
- * gibt es fuer das Format des Strings:
- * <ol>
- * <li><code>"RGB(<i>red</i>,<i>green</i>,<i>blue</i>)"</code><br>
- * wobei <i>red</i>,<i>green</i> und <i>blue</i> dezimale Werte
- * zwischen 0 und 255 sind.</li>
- * <li>Der String stellt einen Integer-Wert im dezimalen, oktalen oder
- * hexadezimalen Format dar, aus dem die 3 RGB-Werte extrahiert werden
- * (siehe {@link Color#decode(String) Color.decode(..)}).</li>
- * <li>Der String spezifiziert ein statisches Feld der Klasse {@link Color}.<br>
- * z.B. steht <code>"RED"</code> fuer {@link Color#RED Color.RED},
- * <code>"darkGray"</code> fuer {@link Color#darkGray Color.darkGray} oder
- * <code>"LIGHT_GRAY"</code> fuer {@link Color#LIGHT_GRAY Color.LIGHT_GRAY}</li>
- * </ol>
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- *
- * @throws IllegalArgumentException wenn der uebergebene String nicht interpretiert werden kann.
- *
- */
- // Schmeisst nur noch IllegalArgumentException, vorher Exception. (SK) 21.08.2007
- public static Color parseColor(String colorStr) throws IllegalArgumentException {
- // Wenn String mit "RGB(" startet, Format RGB(<r>,<b>,<g>) parsen
- if ( colorStr.toUpperCase().startsWith("RGB(") )
- try {
- StringTokenizer tok = new StringTokenizer(colorStr.substring(4));
- int r = Integer.parseInt(tok.nextToken(",()\n"));
- int g = Integer.parseInt(tok.nextToken(",()\n"));
- int b = Integer.parseInt(tok.nextToken(",()\n"));
- return new Color(r,g,b);
- } catch (Exception err) {
- throw new IllegalArgumentException("Invalid RGB-specification. RGB(<r>,<g>,<b>) expected.",err);
- }
+ /**
+ * Fixiert die Groesse einer GUI-Komponente mit der aktuell bevorzugten
+ * Groesse.
+ *
+ * @param comp
+ * GUI-Komponente
+ */
+ public static void fixComponentSize(Component comp) {
+ fixComponentSize(comp, comp.getPreferredSize());
+ }
- // Versucht, die Farbe als dezimalen, oktalen oder hexadezimalen Integer
- // einzulesen
- Long testLong = null;
- try {
- testLong = Long.decode(colorStr);
- return Color.decode(colorStr);
- } catch (NumberFormatException err) {
- // wenn 'testLong' ein gueltiger Long ist, handelt es sich zwar um
- // eine gueltige Zahl, aber kein passendes Integer-Format nicht!
- if ( testLong != null )
- throw new IllegalArgumentException(colorStr + " is not a valid RGB-Integer in decimal, octal or hexadecimal format.");
- }
+ /***
+ * Setzt die Hintergrundfarbe einer Komponente und aller darin enthaltener
+ * Komponenten.
+ *
+ * @param comp
+ * Komponente
+ * @param color
+ * neue Hintergrund-Farbe
+ */
+ public static void setAllBackground(Component comp, Color color) {
+ comp.setBackground(color);
+ if (comp instanceof JFrame)
+ setAllBackground(((JFrame) comp).getContentPane(), color);
+ if (comp instanceof JScrollPane)
+ setAllBackground(((JScrollPane) comp).getViewport(), color);
+ else if (comp instanceof Container)
+ for (Component innerComp : ((Container) comp).getComponents())
+ setAllBackground(innerComp, color);
+ }
- // Wenn auch kein Integer angegeben wurde, wird versucht, die Farbe
- // als Feld von java.awt.Color zu interpretieren
- try {
- return (Color)Color.class.getDeclaredField(colorStr).get(null);
- } catch ( Exception err1 ) {
- try {
- // als letztes noch versuchen, die Farbe in Gross-Buchstaben zu finden
- return (Color) Color.class.getDeclaredField(colorStr.toUpperCase()).get(null);
- } catch ( Exception err2 ) {
- throw new IllegalArgumentException(colorStr + " is not a valid color name. Name of a static field of class java.awt.Color expected.");
- }
- }
- }
+ /**
+ * Versucht, aus einem String eine Farbe zu erstellen. Drei Moeglichekeiten
+ * gibt es fuer das Format des Strings:
+ * <ol>
+ * <li><code>"RGB(<i>red</i>,<i>green</i>,<i>blue</i>)"</code><br>
+ * wobei <i>red</i>,<i>green</i> und <i>blue</i> dezimale Werte zwischen 0
+ * und 255 sind.</li>
+ * <li>Der String stellt einen Integer-Wert im dezimalen, oktalen oder
+ * hexadezimalen Format dar, aus dem die 3 RGB-Werte extrahiert werden
+ * (siehe {@link Color#decode(String) Color.decode(..)}).</li>
+ * <li>Der String spezifiziert ein statisches Feld der Klasse {@link Color}.
+ * <br>
+ * z.B. steht <code>"RED"</code> fuer {@link Color#RED Color.RED},
+ * <code>"darkGray"</code> fuer {@link Color#darkGray Color.darkGray} oder
+ * <code>"LIGHT_GRAY"</code> fuer {@link Color#LIGHT_GRAY Color.LIGHT_GRAY}</li>
+ * </ol>
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ *
+ * @throws IllegalArgumentException
+ * wenn der uebergebene String nicht interpretiert werden kann.
+ *
+ */
+ // Schmeisst nur noch IllegalArgumentException, vorher Exception. (SK)
+ // 21.08.2007
+ public static Color parseColor(String colorStr)
+ throws IllegalArgumentException {
+ // Wenn String mit "RGB(" startet, Format RGB(<r>,<b>,<g>) parsen
+ if (colorStr.toUpperCase().startsWith("RGB("))
+ try {
+ StringTokenizer tok = new StringTokenizer(colorStr.substring(4));
+ int r = Integer.parseInt(tok.nextToken(",()\n"));
+ int g = Integer.parseInt(tok.nextToken(",()\n"));
+ int b = Integer.parseInt(tok.nextToken(",()\n"));
+ return new Color(r, g, b);
+ } catch (Exception err) {
+ throw new IllegalArgumentException(
+ "Invalid RGB-specification. RGB(<r>,<g>,<b>) expected.",
+ err);
+ }
- /**
- * Versucht, aus einem String eine Farbe zu erstellen. Drei Moeglichekeiten
- * gibt es fuer das Format des Strings:
- * <ol>
- * <li><code>"RGB(<i>red</i>,<i>green</i>,<i>blue</i>)"</code><br>
- * wobei <i>red</i>,<i>green</i> und <i>blue</i> dezimale Werte
- * zwischen 0 und 255 sind.</li>
- * <li>Der String stellt einen Integer-Wert im dezimalen, oktalen oder
- * hexadezimalen Format dar, aus dem die 3 RGB-Werte extrahiert werden
- * (siehe {@link Color#decode(String) Color.decode(..)}).</li>
- * <li>Der String spezifiziert ein statisches Feld der Klasse {@link Color}.<br>
- * z.B. steht <code>"RED"</code> fuer {@link Color#RED Color.RED},
- * <code>"darkGray"</code> fuer {@link Color#darkGray Color.darkGray} oder
- * <code>"LIGHT_GRAY"</code> fuer {@link Color#LIGHT_GRAY Color.LIGHT_GRAY}</li>
- * </ol>
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a> (University of Bonn/Germany)
- *
- * @throws IllegalArgumentException wenn der uebergebene String nicht interpretiert werden kann.
- *
- */
- // Schmeisst nur noch IllegalArgumentException, vorher Exception. (SK) 21.08.2007
- public static String convertColorToHex(Color color) {
- int r = color.getRed();
- int g = color.getGreen();
- int b = color.getBlue();
+ // Versucht, die Farbe als dezimalen, oktalen oder hexadezimalen Integer
+ // einzulesen
+ Long testLong = null;
+ try {
+ testLong = Long.decode(colorStr);
+ return Color.decode(colorStr);
+ } catch (NumberFormatException err) {
+ // wenn 'testLong' ein gueltiger Long ist, handelt es sich zwar um
+ // eine gueltige Zahl, aber kein passendes Integer-Format nicht!
+ if (testLong != null)
+ throw new IllegalArgumentException(
+ colorStr
+ + " is not a valid RGB-Integer in decimal, octal or hexadecimal format.");
+ }
- // Convert RGB to 2-digit Hex
- String rHex = Integer.toHexString(r);
- if ( rHex.length() < 2 )
- rHex = "0" + rHex;
- String gHex = Integer.toHexString(g);
- if ( gHex.length() < 2 )
- gHex = "0" + gHex;
- String bHex = Integer.toHexString(b);
- if ( bHex.length() < 2 )
- bHex = "0" + bHex;
-
- // combine RGB to Hex string
- return "#"+rHex+gHex+bHex;
- }
+ // Wenn auch kein Integer angegeben wurde, wird versucht, die Farbe
+ // als Feld von java.awt.Color zu interpretieren
+ try {
+ return (Color) Color.class.getDeclaredField(colorStr).get(null);
+ } catch (Exception err1) {
+ try {
+ // als letztes noch versuchen, die Farbe in Gross-Buchstaben zu
+ // finden
+ return (Color) Color.class.getDeclaredField(
+ colorStr.toUpperCase()).get(null);
+ } catch (Exception err2) {
+ throw new IllegalArgumentException(
+ colorStr
+ + " is not a valid color name. Name of a static field of class java.awt.Color expected.");
+ }
+ }
+ }
- /**
- * Setzt das Label eine Componente neu. Macht nichts, falls {@code newLabel}
- * oder {@code comp} den Wert {@code null} hat.
- * @param comp {@link JLabel}, {@link AbstractButton}, {@link JDialog} oder
- * {@link Frame}
- * @param newLabel neue Beschriftung
- * @exception UnsupportedOperationException falls {@code comp} nicht
- * unterstuetzt wird.
- *
- */
- public static void resetCaption(Component comp, Object newLabel) {
- if ( comp == null || newLabel == null )
- return;
- if ( comp instanceof JLabel )
- ((JLabel)comp).setText( newLabel.toString() );
- else if ( comp instanceof AbstractButton )
- ((AbstractButton)comp).setText( newLabel.toString() );
- else if ( comp instanceof Frame )
- ((Frame)comp).setTitle( newLabel.toString() );
- else if ( comp instanceof JDialog )
- ((JDialog)comp).setTitle( newLabel.toString() );
- else
- throw new UnsupportedOperationException(SwingUtil.class.getSimpleName()+"resetCaption(.) can not be applied to "+comp.getClass().getSimpleName());
- }
+ /**
+ * Versucht, aus einem String eine Farbe zu erstellen. Drei Moeglichekeiten
+ * gibt es fuer das Format des Strings:
+ * <ol>
+ * <li><code>"RGB(<i>red</i>,<i>green</i>,<i>blue</i>)"</code><br>
+ * wobei <i>red</i>,<i>green</i> und <i>blue</i> dezimale Werte zwischen 0
+ * und 255 sind.</li>
+ * <li>Der String stellt einen Integer-Wert im dezimalen, oktalen oder
+ * hexadezimalen Format dar, aus dem die 3 RGB-Werte extrahiert werden
+ * (siehe {@link Color#decode(String) Color.decode(..)}).</li>
+ * <li>Der String spezifiziert ein statisches Feld der Klasse {@link Color}.
+ * <br>
+ * z.B. steht <code>"RED"</code> fuer {@link Color#RED Color.RED},
+ * <code>"darkGray"</code> fuer {@link Color#darkGray Color.darkGray} oder
+ * <code>"LIGHT_GRAY"</code> fuer {@link Color#LIGHT_GRAY Color.LIGHT_GRAY}</li>
+ * </ol>
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ *
+ * @throws IllegalArgumentException
+ * wenn der uebergebene String nicht interpretiert werden kann.
+ *
+ */
+ // Schmeisst nur noch IllegalArgumentException, vorher Exception. (SK)
+ // 21.08.2007
+ public static String convertColorToHex(Color color) {
+ int r = color.getRed();
+ int g = color.getGreen();
+ int b = color.getBlue();
- /**
- * Erstellt das Pattern fuer ein {@link NumberFormat}.
- * @param sample Beispiel-Wert, der die Anzahl der dargestellten Nachkomma-Stellen
- * bestimmt
- */
- public static String getNumberFormatPattern(double sample) {
- String format = "0";
- for (int i=0; sample != (int)sample; i++ ) {
- if ( i==0 )
- format += ".";
- sample *= 10;
- format += "0";
- }
- return format;
- }
+ // Convert RGB to 2-digit Hex
+ String rHex = Integer.toHexString(r);
+ if (rHex.length() < 2)
+ rHex = "0" + rHex;
+ String gHex = Integer.toHexString(g);
+ if (gHex.length() < 2)
+ gHex = "0" + gHex;
+ String bHex = Integer.toHexString(b);
+ if (bHex.length() < 2)
+ bHex = "0" + bHex;
- /**
- * Erstellt das Pattern fuer ein {@link NumberFormat}.
- * @param digits Anzahl der dargestellten Nachkomma-Stellen
- */
- public static String getNumberFormatPattern(int digits) {
- String format = "0";
- for (int i=0; i<digits; i++ ) {
- if ( i==0 )
- format += ".";
- format += "0";
- }
- return format;
- }
+ // combine RGB to Hex string
+ return "#" + rHex + gHex + bHex;
+ }
- /**
- * Copied from http://www.exampledepot.com/egs/javax.swing.tree/ExpandAll.html
- * e1029. Expanding or Collapsing All Nodes in a JTree Component
- * If expand is true, expands all nodes in the tree.
- * Otherwise, collapses all nodes in the tree.
- * @param tree {@link JTree} to expand or collapse
- */
- public static void expandAll(JTree tree, boolean expand) {
- TreeNode root = (TreeNode)tree.getModel().getRoot();
+ /**
+ * Setzt das Label eine Componente neu. Macht nichts, falls {@code newLabel}
+ * oder {@code comp} den Wert {@code null} hat.
+ *
+ * @param comp
+ * {@link JLabel}, {@link AbstractButton}, {@link JDialog} oder
+ * {@link Frame}
+ * @param newLabel
+ * neue Beschriftung
+ * @exception UnsupportedOperationException
+ * falls {@code comp} nicht unterstuetzt wird.
+ *
+ */
+ public static void resetCaption(Component comp, Object newLabel) {
+ if (comp == null || newLabel == null)
+ return;
+ if (comp instanceof JLabel)
+ ((JLabel) comp).setText(newLabel.toString());
+ else if (comp instanceof AbstractButton)
+ ((AbstractButton) comp).setText(newLabel.toString());
+ else if (comp instanceof Frame)
+ ((Frame) comp).setTitle(newLabel.toString());
+ else if (comp instanceof JDialog)
+ ((JDialog) comp).setTitle(newLabel.toString());
+ else
+ throw new UnsupportedOperationException(SwingUtil.class
+ .getSimpleName()
+ + "resetCaption(.) can not be applied to "
+ + comp.getClass().getSimpleName());
+ }
- // Traverse tree from root
- expandAll(tree, new TreePath(root), expand);
- }
- private static void expandAll(JTree tree, TreePath parent, boolean expand) {
- // Traverse children
- TreeNode node = (TreeNode)parent.getLastPathComponent();
- if (node.getChildCount() >= 0) {
- for (Enumeration e=node.children(); e.hasMoreElements(); ) {
- TreeNode n = (TreeNode)e.nextElement();
- TreePath path = parent.pathByAddingChild(n);
- expandAll(tree, path, expand);
- }
- }
+ /**
+ * Erstellt das Pattern fuer ein {@link NumberFormat}.
+ *
+ * @param sample
+ * Beispiel-Wert, der die Anzahl der dargestellten
+ * Nachkomma-Stellen bestimmt
+ */
+ public static String getNumberFormatPattern(double sample) {
+ String format = "0";
+ for (int i = 0; sample != (int) sample; i++) {
+ if (i == 0)
+ format += ".";
+ sample *= 10;
+ format += "0";
+ }
+ return format;
+ }
- // Expansion or collapse must be done bottom-up
- if (expand) {
- tree.expandPath(parent);
- } else {
- tree.collapsePath(parent);
- }
- }
+ /**
+ * Erstellt das Pattern fuer ein {@link NumberFormat}.
+ *
+ * @param digits
+ * Anzahl der dargestellten Nachkomma-Stellen
+ */
+ public static String getNumberFormatPattern(int digits) {
+ String format = "0";
+ for (int i = 0; i < digits; i++) {
+ if (i == 0)
+ format += ".";
+ format += "0";
+ }
+ return format;
+ }
- /**
- * This method maximizes a frame; the iconified bit is not affected
- * Taken from e564. Iconifying and Maximizing a Frame,
- * http://www.exampledepot.com/egs/java.awt/frame_FrameIconify.html
- *
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Krüger</a>
- */
- public static void maximize(Frame frame) {
- int state = frame.getExtendedState();
+ /**
+ * Copied from
+ * http://www.exampledepot.com/egs/javax.swing.tree/ExpandAll.html e1029.
+ * Expanding or Collapsing All Nodes in a JTree Component If expand is true,
+ * expands all nodes in the tree. Otherwise, collapses all nodes in the
+ * tree.
+ *
+ * @param tree
+ * {@link JTree} to expand or collapse
+ */
+ public static void expandAll(JTree tree, boolean expand) {
+ TreeNode root = (TreeNode) tree.getModel().getRoot();
- // Set the maximized bits
- state |= Frame.MAXIMIZED_BOTH;
+ // Traverse tree from root
+ expandAll(tree, new TreePath(root), expand);
+ }
- // Maximize the frame
- frame.setExtendedState(state);
- }
+ private static void expandAll(JTree tree, TreePath parent, boolean expand) {
+ // Traverse children
+ TreeNode node = (TreeNode) parent.getLastPathComponent();
+ if (node.getChildCount() >= 0) {
+ for (Enumeration e = node.children(); e.hasMoreElements();) {
+ TreeNode n = (TreeNode) e.nextElement();
+ TreePath path = parent.pathByAddingChild(n);
+ expandAll(tree, path, expand);
+ }
+ }
+ // Expansion or collapse must be done bottom-up
+ if (expand) {
+ tree.expandPath(parent);
+ } else {
+ tree.collapsePath(parent);
+ }
+ }
+
+ /**
+ * This method maximizes a frame; the iconified bit is not affected Taken
+ * from e564. Iconifying and Maximizing a Frame,
+ * http://www.exampledepot.com/egs/java.awt/frame_FrameIconify.html
+ *
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static void maximize(Frame frame) {
+ int state = frame.getExtendedState();
+
+ // Set the maximized bits
+ state |= Frame.MAXIMIZED_BOTH;
+
+ // Maximize the frame
+ frame.setExtendedState(state);
+ }
+
+ /**
+ * This method deiconifies a frame; the maximized bits are not affected.
+ *
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+ * Krüger</a>
+ */
+ public static void deiconify(JFrame frame) {
+ int state = frame.getExtendedState();
+
+ // Clear the iconified bit
+ state &= ~Frame.ICONIFIED;
+
+ // Deiconify the frame
+ frame.setExtendedState(state);
+
+ }
+
}
More information about the Schmitzm-commits
mailing list