[Schmitzm-commits] r530 - in branches/1.0-gt2-2.6/src: gtmig/org/geotools/swing schmitzm/swing skrueger/geotools

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Thu Nov 19 10:31:16 CET 2009


Author: alfonx
Date: 2009-11-19 10:31:14 +0100 (Thu, 19 Nov 2009)
New Revision: 530

Modified:
   branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java
   branches/1.0-gt2-2.6/src/schmitzm/swing/SwingUtil.java
   branches/1.0-gt2-2.6/src/skrueger/geotools/RenderingExecutor.java
Log:
* More cleanup and documentation

Modified: branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java
===================================================================
--- branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java	2009-11-18 20:47:00 UTC (rev 529)
+++ branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java	2009-11-19 09:31:14 UTC (rev 530)
@@ -1,25 +1,5 @@
-/*
- *    GeoTools - OpenSource mapping toolkit
- *    http://geotools.org
- *    (C) 2002-2006, GeoTools Project Managment Committee (PMC)
- *
- *    This library is free software; you can redistribute it and/or
- *    modify it under the terms of the GNU Lesser General Public
- *    License as published by the Free Software Foundation;
- *    version 2.1 of the License.
- *
- *    This library is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *    Lesser General Public License for more details.
- */
 package gtmig.org.geotools.swing;
 
-/**
- * This class is 50% copied from GeoTools 2.6.x JMapPane. GeoTools is LGPL, SCHMITZM also.<br/>
- * In addition to 
- */
-
 import java.awt.Color;
 import java.awt.Cursor;
 import java.awt.Font;
@@ -45,7 +25,6 @@
 import java.util.Map;
 import java.util.Vector;
 
-import javax.swing.JPanel;
 import javax.swing.Timer;
 
 import org.apache.log4j.Logger;
@@ -81,83 +60,102 @@
 import schmitzm.geotools.map.event.JMapPaneListener;
 import schmitzm.geotools.map.event.MapLayerAdapter;
 import schmitzm.lang.LangUtil;
+import schmitzm.swing.JPanel;
 import schmitzm.swing.SwingUtil;
 import skrueger.geotools.RenderingExecutor;
-import skrueger.swing.formatter.MbDecimalFormatter;
 
 import com.vividsolutions.jts.geom.Coordinate;
 import com.vividsolutions.jts.geom.Envelope;
 import com.vividsolutions.jts.geom.Geometry;
 
+/**
+ * The {@link XMapPane} class uses a Geotools {@link GTRenderer} to paint up to
+ * two {@link MapContext}s: a "local" {@link MapContext} and a "background"
+ * {@link MapContext}. The idea is, that rendering a background layer made up of
+ * e.g. OSM data, may take much longer than rendering local data.<br>
+ * Every {@link MapContext} is rendered on a {@link Thread} of it's own.
+ * Starting/ cancelling these threads is done by the {@link RenderingExecutor}.<br>
+ * <br>
+ * While the renderers are rending the map, a <br>
+ * The {@link XMapPane} is based on schmitzm {@link JPanel}, so
+ * {@link #print(Graphics)} will automatically set the background of components
+ * to pure white.
+ * 
+ * The XMapPane has a {@link MouseListener} that manages zooming.<br>
+ * A logo/icon to float in the lower left corner may be set with
+ * {@link #setMapImage(BufferedImage)}<br>
+ * 
+ * @see SelectableXMapPane - an extension of {@link XMapPane} that supports
+ *      selecting features.
+ * 
+ * @author stefan
+ * 
+ */
 public class XMapPane extends JPanel {
+
+	private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
+	private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;
+
 	private static Logger LOGGER = Logger.getLogger(XMapPane.class);
 
+	private boolean acceptsRepaintCalls = true;
+
 	/**
-	 * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
-	 * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
-	 * 
-	 * @param layer
-	 *            a layer
-	 * @param selectable
-	 *            if {@code false} the layer is ignored during the upper
-	 *            mentioned actions. If <code>null</code>, the default (true)
-	 *            will be used.
+	 * Main {@link MapContext} that holds all layers that are rendered into the
+	 * {@link #localImage} by the {@link #localRenderer}
 	 */
-	public void setMapLayerSelectable(MapLayer layer, Boolean selectable) {
-		if (selectable == null)
-			mapLayerSelectable.remove(layer);
-		else
-			mapLayerSelectable.put(layer, selectable);
-	}
+	MapContext localContext;
 
 	/**
-	 * Holds a flag for each layer, whether it is regarded or ignored on
-	 * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}
-	 * actions.
+	 * {@link MapContext} holding the background layers. Use it for layers that
+	 * CAN take very long for rendering, like layer from the Internet: WMS, WFS,
+	 * OSM...<br>
+	 * <code>null</code> by default.
+	 * 
+	 * @see #setBgContext(MapContext)
+	 * @see #getBgContext()
 	 */
-	final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
+	MapContext bgContext;
 
 	/**
-	 * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
-	 * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns
-	 * <code>true</code> if the selectability has not been defined.
+	 * While threads are working, calls {@link XMapPane#updateFinalImage()}
+	 * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
+	 * renderers have finished.
 	 * 
-	 * @param layer
-	 *            a layer
+	 * @see #INITIAL_REPAINT_DELAYAL
+	 * @see #REPEATING_REPAINT_DELAY
 	 */
-	public boolean isMapLayerSelectable(MapLayer layer) {
-		Boolean selectable = mapLayerSelectable.get(layer);
-		return selectable == null ? true : selectable;
-	}
+	final private Timer repaintTimer;
 
 	/**
-	 * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
-	 * moeglich!
-	 * 
-	 * @see #setState(int)
+	 * The initial delay in milliseconds until the {@link #finalImage} is
+	 * updated the first time.
 	 */
-	public static final int PAN = 1;
+	public static final int INITIAL_REPAINT_DELAY = 1000;
+
 	/**
-	 * Flag fuer Modus "Heran zoomen".
-	 * 
-	 * @see #setState(int)
-	 * @see #setState(int)
+	 * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
+	 * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
+	 * with previews.
 	 */
-	public static final int ZOOM_IN = 2;
+	public static final long REPEATING_REPAINT_DELAY = 500;
+
 	/**
-	 * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
-	 * 
-	 * @see #setState(int)
+	 * Default delay (milliseconds) before the map will be redrawn when resizing
+	 * the pane. This is to avoid flickering while drag-resizing.
 	 */
-	public static final int ZOOM_OUT = 3;
+	public static final int DEFAULT_RESIZING_PAINT_DELAY = 500;
+
+	public static final int NONE = -123;
+
 	/**
-	 * Flag fuer Modus
-	 * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
+	 * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
+	 * moeglich!
 	 * 
 	 * @see #setState(int)
-	 * @see #setState(int)
 	 */
-	public static final int SELECT_TOP = 4;
+	public static final int PAN = 1;
+
 	/**
 	 * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
 	 * 
@@ -173,72 +171,48 @@
 	 * @see #setState(int)
 	 */
 	public static final int SELECT_ONE_FROM_TOP = 104;
-
 	/**
-	 * While threads are working, we call {@link XMapPane#updateFinalImage()}
-	 * regularly and repaint(). This {@link Timer} is stopped when all renderers
-	 * have finished.
+	 * Flag fuer Modus
+	 * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
+	 * 
+	 * @see #setState(int)
+	 * @see #setState(int)
 	 */
-	final private Timer repainterTimer;
+	public static final int SELECT_TOP = 4;
 
-	/**
-	 * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
-	 * the {@link #repainterTimer} is regularly updating the {@link #finalImage}
-	 * with previews.
-	 */
-	public static final long REPEATING_REPAINT_DELAY = 500;
+	public static final Cursor WAIT_CURSOR = Cursor
+			.getPredefinedCursor(Cursor.WAIT_CURSOR);
 
-	/**
-	 * The initial delay in milliseconds until the {@link #finalImage} is
-	 * updated the first time.
-	 */
-	public static final long INITIAL_REPAINT_DELAY = 1000;
+	final static Font waitFont = new Font("Arial", Font.BOLD, 30);
 
-	protected RenderingExecutor bgExecuter;
-
 	/**
-	 * the map context to render
+	 * Flag fuer Modus "Heran zoomen".
+	 * 
+	 * @see #setState(int)
+	 * @see #setState(int)
 	 */
-	MapContext localContext;
-	/**
-	 * the map context to render
-	 */
-	MapContext bgContext;
+	public static final int ZOOM_IN = 2;
 
 	/**
-	 * the area of the map to draw
+	 * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
+	 * 
+	 * @see #setState(int)
 	 */
-	protected Envelope mapArea = null;
-	/**
-	 * We store the old mapArea for a moment to use it for the
-	 * "quick scaled preview" in case of ZoomOut
-	 **/
-	protected Envelope oldMapArea = null;
+	public static final int ZOOM_OUT = 3;
 
 	/**
-	 * compass and icon are rendered into this image
-	 */
-	// protected BufferedImage gadgetsImage;
-
-	/**
-	 * The default state is ZOOM_IN, hence by default the
-	 * {@link #zoomMapPaneMouseListener} is also enabled.
-	 **/
-	private int state = ZOOM_IN;
-
-	/**
 	 * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
 	 * Karten-Koordinaten.
 	 * 
 	 * @param e
 	 *            Maus-Ereignis
 	 */
-	public static Point2D getMapCoordinatesFromEvent(MouseEvent e) {
+	public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {
 		// aktuelle Geo-Position aus GeoMouseEvent ermitteln
 		if (e != null && e instanceof MapMouseEvent)
 			try {
 				return ((MapMouseEvent) e).getMapPosition().toPoint2D();
-			} catch (Exception err) {
+			} catch (final Exception err) {
 				LOGGER
 						.error(
 								"return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
@@ -253,7 +227,7 @@
 			if (!xMapPane.isWellDefined())
 				return null;
 
-			AffineTransform at = xMapPane.getScreenToWorld();
+			final AffineTransform at = xMapPane.getScreenToWorld();
 			if (at != null)
 				return at.transform(e.getPoint(), null);
 			return null;
@@ -263,32 +237,281 @@
 	}
 
 	/**
+	 * Listens to changes of the "background" {@link MapContext} and triggers
+	 * repaints where needed.
+	 */
+	private final MapLayerListListener bgContextListener = new MapLayerListListener() {
+
+		@Override
+		public void layerAdded(final MapLayerListEvent event) {
+			event.getLayer().addMapLayerListener(bgMapLayerListener);
+
+			if (localContext.getLayers().length == 0
+					&& bgContext.getLayers().length == 1) { // the first one and
+				// localContext is
+				// empty
+				if (!setMapArea(localContext.getAreaOfInterest()))
+					requestStartRendering();
+				return;
+			}
+
+			// We need to redraw, even in case that the mapArea didn't change
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+
+		}
+
+		@Override
+		public void layerChanged(final MapLayerListEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerMoved(final MapLayerListEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerRemoved(final MapLayerListEvent event) {
+			if (event.getLayer() != null)
+				event.getLayer().removeMapLayerListener(bgMapLayerListener);
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+	};
+
+	/**
+	 * compass and icon are rendered into this image
+	 */
+	// protected BufferedImage gadgetsImage;
+
+	protected RenderingExecutor bgExecuter;
+
+	/**
+	 * The Renderer for the LocalLayers uses this Image. When set to null,
+	 * please dispose this {@link Graphics2D}
+	 */
+	private BufferedImage localImage;
+
+	private BufferedImage finalImage;
+	/**
+	 * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background
+	 * uses this Image. When set to null, please dispose the {@link Graphics2D}
+	 */
+	private BufferedImage bgImage;
+
+	/**
+	 * Optionally a transparent image to paint over the map in the lower right
+	 * corner.
+	 * 
+	 * @see #addGadgets(Graphics2D)
+	 * @see #setMapImage(BufferedImage)
+	 **/
+	private BufferedImage mapImage = null;
+
+	/**
+	 * Listens to each layer in the local {@link MapContext} for changes and
+	 * triggers repaints.
+	 */
+	protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
+
+		@Override
+		public void layerChanged(final MapLayerEvent event) {
+			// Change of SLD for example
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerHidden(final MapLayerEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerShown(final MapLayerEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+	};
+
+	/**
+	 * A flag indicating if dispose() was already called. If true, then further
+	 * use of this {@link SelectableXMapPane} is undefined.
+	 */
+	private boolean disposed = false;
+
+	/**
+	 * While dragging, the {@link #updateFinalImage()} method is translating the
+	 * cached images while setting it together.
+	 **/
+	Point imageOrigin = new Point(0, 0);
+	/**
+	 * For every rendering thread started,
+	 * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
+	 * renderer. These Java2D rendering hints are passed to the
+	 * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
+	 * and local).
+	 */
+	private RenderingHints java2dHints;
+
+	protected LabelCache labelCache = new LabelCacheImpl();
+
+	/**
+	 * Listens to changes of the "local" {@link MapContext} and triggers
+	 * repaints where needed.
+	 */
+	private final MapLayerListListener localContextListener = new MapLayerListListener() {
+
+		@Override
+		public void layerAdded(final MapLayerListEvent event) {
+			event.getLayer().addMapLayerListener(localMapLayerListener);
+
+			localRenderer.setContext(getContext());
+
+			if (localContext.getLayers().length == 1) { // the first one
+				// if the Area of Interest is unset, the LayerBounds are used
+				if (!setMapArea(localContext.getAreaOfInterest()))
+					repaint();
+
+				return;
+			}
+
+			// We need to redraw, even in case that the mapArea didn't change
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+
+		}
+
+		@Override
+		public void layerChanged(final MapLayerListEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			localRenderer.setContext(getContext());
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerMoved(final MapLayerListEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			localRenderer.setContext(getContext());
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerRemoved(final MapLayerListEvent event) {
+			if (event.getLayer() != null)
+				event.getLayer().removeMapLayerListener(localMapLayerListener);
+			// mapImageInvalid = true;
+			// repaint();
+			localRenderer.setContext(getContext());
+			requestStartRendering();
+		}
+	};
+
+	private final RenderingExecutor localExecuter = new RenderingExecutor(this);
+
+	/**
+	 * Listens to each layer in the local {@link MapContext} for changes and
+	 * triggers repaints.
+	 */
+	protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
+
+		@Override
+		public void layerChanged(final MapLayerEvent event) {
+			localRenderer.setContext(getContext()); // betters for SLD changes?!
+			// Change of SLD for example
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerHidden(final MapLayerEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+
+		@Override
+		public void layerShown(final MapLayerEvent event) {
+			// mapImageInvalid = true;
+			// repaint();
+			requestStartRendering();
+		}
+	};
+
+	private final GTRenderer localRenderer = GTUtil.createGTRenderer();
+	
+	private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
+
+	/**
+	 * the area of the map to draw
+	 */
+	protected Envelope mapArea = null;
+
+	/**
+	 * A flag set it {@link #setMapArea(Envelope)} to indicated the
+	 * {@link #paintComponent(Graphics)} method, that the image on-screen is
+	 * associated with {@link #oldMapArea} and may hence be scaled for a quick
+	 * preview.<br>
+	 * The flag is reset
+	 **/
+	private boolean mapAreaChanged = false;
+
+	/**
+	 * This color is used as the default background color when painting a map.
+	 */
+	private Color mapBackgroundColor = Color.WHITE;
+
+	/**
 	 * A flag indicating that the shown image is invalid and needs to be
 	 * re-rendered.
 	 */
 	protected boolean mapImageInvalid = true;
 
-	protected LabelCache labelCache = new LabelCacheImpl();
+	/**
+	 * Holds a flag for each layer, whether it is regarded or ignored on
+	 * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}
+	 * actions.
+	 */
+	final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
 
 	/**
+	 * List of listeners of this {@link XMapPane}
+	 */
+	protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
+	/**
 	 * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
 	 * out of that area
 	 **/
 	private Envelope maxExtend = null;
+	private Double maxZoomScale = Double.MIN_VALUE;
 
-	private Double maxZoomScale = Double.MIN_VALUE;
 	private Double minZoomScale = Double.MAX_VALUE;
 
 	/**
-	 * This color is used as the default background color when painting a map.
-	 */
-	private Color mapBackgroundColor = Color.WHITE;
+	 * We store the old mapArea for a moment to use it for the
+	 * "quick scaled preview" in case of ZoomOut
+	 **/
+	protected Envelope oldMapArea = null;
 
 	/**
-	 * This {@link MouseListener} is managing all zoom related tasks
-	 */
-	public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
-			this);
+	 * We store the old transform for a moment to use it for the
+	 * "quick scaled preview" in case of ZoomIn
+	 **/
+	protected AffineTransform oldScreenToWorld = null;
 
 	/**
 	 * A flag indicating, that the image size has changed and the buffered
@@ -296,37 +519,55 @@
 	 **/
 	protected boolean paneResized = false;
 
+	private BufferedImage preFinalImage;
+
+	// if null, no quick preview will be shown
+	private int quickPreviewHint = 0;
+
+	private Map<Object, Object> rendererHints;
+
+	private volatile Boolean requestStartRendering = false;
+
+	private final Timer resizeTimer;
+
+	private final int resizingPaintDelay;
+
 	/**
+	 * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
+	 * (lat/lon)
+	 */
+	protected AffineTransform screenToWorld = null;
+
+	/**
 	 * The flag {@link #requestStartRendering} can be set to true by events.
 	 * This {@link Timer} checks the flag regularly and starts one renderer
 	 * thread.
 	 */
 	final private Timer startRenderThreadsTimer;
 
-	private Map<Object, Object> rendererHints;
+	/**
+	 * The default state is ZOOM_IN, hence by default the
+	 * {@link #zoomMapPaneMouseListener} is also enabled.
+	 **/
+	private int state = ZOOM_IN;
 
-	public Map<Object, Object> getRendererHints() {
-		return rendererHints;
-	}
+	/**
+	 * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
+	 * MapPane-Funktion
+	 */
+	protected Cursor staticCursor = null;
 
+	private AffineTransform worldToScreen;
+
 	/**
-	 * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot gemacht
-	 * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
+	 * This {@link MouseListener} is managing all zoom related tasks
 	 */
-	@Override
-	public void print(Graphics g) {
-		Color orig = getBackground();
-		setBackground(Color.WHITE);
+	public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
+			this);
 
-		// wrap in try/finally so that we always restore the state
-		try {
-			super.print(g);
-		} finally {
-			setBackground(orig);
-		}
+	// TODO doku
+	public XMapPane() {
+		this(null, null);
 	}
 
 	/**
@@ -344,14 +585,13 @@
 	 *            - {@link MapContext} of layer to render.
 	 */
 	public XMapPane(final MapContext localContext_,
-			Map<Object, Object> rendererHints) {
+			final Map<Object, Object> rendererHints) {
 		super(true);
 
 		setRendererHints(rendererHints);
 
 		setOpaque(true);
 
-		localRenderer = GTUtil.createGTRenderer();
 		localRenderer.setJava2DHints(getJava2dHints());
 
 		if (localContext_ != null)
@@ -374,16 +614,17 @@
 		resizingPaintDelay = DEFAULT_RESIZING_PAINT_DELAY;
 		resizeTimer = new Timer(resizingPaintDelay, new ActionListener() {
 
-			public void actionPerformed(ActionEvent e) {
+			public void actionPerformed(final ActionEvent e) {
 				paneResized = true;
 
 				if (!isWellDefined())
 					return;
 
-				Rectangle bounds = getVisibleRect();
+				final Rectangle bounds = getVisibleRect();
 
-				Envelope geoMapArea = tranformWindowToGeo(bounds.x, bounds.y,
-						bounds.x + bounds.width, bounds.y + bounds.height);
+				final Envelope geoMapArea = tranformWindowToGeo(bounds.x,
+						bounds.y, bounds.x + bounds.width, bounds.y
+								+ bounds.height);
 
 				setMapArea(bestAllowedMapArea(geoMapArea));
 			}
@@ -392,7 +633,7 @@
 		this.addComponentListener(new ComponentAdapter() {
 
 			@Override
-			public void componentResized(ComponentEvent e) {
+			public void componentResized(final ComponentEvent e) {
 				if (bgExecuter != null)
 					bgExecuter.cancelTask();
 				if (localExecuter != null)
@@ -402,22 +643,29 @@
 
 		});
 
-		repainterTimer = new Timer((int) REPEATING_REPAINT_DELAY,
+		/*
+		 * Setting up the repaintTimer. Not started automatically.
+		 */
+		repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,
 				new ActionListener() {
 
 					@Override
-					public void actionPerformed(ActionEvent e) {
+					public void actionPerformed(final ActionEvent e) {
 						updateFinalImage();
 						XMapPane.this.repaint();
 					}
 				});
-		repainterTimer.setInitialDelay(300);
-		repainterTimer.setRepeats(true);
+		repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
+		repaintTimer.setRepeats(true);
 
+		/*
+		 * Setting up the startRenderThreadsTimer. This Timer starts
+		 * automatically.
+		 */
 		startRenderThreadsTimer = new Timer(100, new ActionListener() {
 
 			@Override
-			public void actionPerformed(ActionEvent e) {
+			public void actionPerformed(final ActionEvent e) {
 				synchronized (requestStartRendering) {
 					if (requestStartRendering && isWellDefined()) {
 
@@ -435,461 +683,522 @@
 
 	}
 
-	// TODO doku
-	public XMapPane() {
-		this(null, null);
+	/**
+	 * Fuegt der Map einen Listener hinzu.
+	 * 
+	 * @param l
+	 *            neuer Listener
+	 */
+	public void addMapPaneListener(final JMapPaneListener l) {
+		mapPaneListeners.add(l);
 	}
 
 	/**
-	 * Sets the mapArea to best possibly present the given features. If only one
-	 * single point is given, the window is moved over the point.
+	 * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
+	 * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
+	 * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br>
+	 * Since 21. April 09: Before thecalculation starts, the aspect ratio is
+	 * corrected. This change implies, that setMapArea() will most of the time
+	 * not allow setting to a wrong aspectRatio.
 	 * 
-	 * Note: The method does not call {@link #repaint()} on the
-	 * {@link SelectableXMapPane} .
-	 * 
-	 * @param features
-	 *            if <code>null</code> or size==0, the function doesn nothing.
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	 *         Kr&uuml;ger</a>
 	 */
-	public void zoomTo(
-			FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
+	public Envelope bestAllowedMapArea(Envelope env) {
+		if (getWidth() == 0)
+			return env;
+		if (env == null)
+			return null;
 
-		CoordinateReferenceSystem mapCRS = getContext()
-				.getCoordinateReferenceSystem();
-		CoordinateReferenceSystem fCRS = features.getSchema()
-				.getGeometryDescriptor().getCoordinateReferenceSystem();
+		Envelope newArea = null;
 
-		double width = mapArea.getWidth();
-		double height = mapArea.getHeight();
-		double ratio = height / width;
+		/**
+		 * Correct the aspect Ratio before we check the rest. Otherwise we might
+		 * easily fail. We allow to grow here, because we don't check against
+		 * the maxExtend
+		 */
+		final Rectangle curPaintArea = getVisibleRect();
 
-		if (features == null || features.size() == 0) {
-			// feature count == 0 Zoom to the full extend
-			return;
-		} else if (features.size() == 1) {
+		env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
 
-			// feature count == 1 Just move the window to the point and zoom 'a
-			// bit'
-			SimpleFeature singleFeature = (SimpleFeature) features.iterator()
-					.next();
+		final double scale = env.getWidth() / getWidth();
+		final double centerX = env.getMinX() + env.getWidth() / 2.;
+		final double centerY = env.getMinY() + env.getHeight() / 2.;
+		double newWidth2 = 0;
+		double newHeight2 = 0;
+		if (scale < getMaxZoomScale()) {
+			// ****************************************************************************
+			// Wir zoomen weiter rein als erlaubt => Anpassen des envelope
+			// ****************************************************************************
+			newWidth2 = getMaxZoomScale() * getWidth() / 2.;
+			newHeight2 = getMaxZoomScale() * getHeight() / 2.;
+		} else if (scale > getMinZoomScale()) {
+			// ****************************************************************************
+			// Wir zoomen weiter raus als erlaubt => Anpassen des envelope
+			// ****************************************************************************
+			newWidth2 = getMinZoomScale() * getWidth() / 2.;
+			newHeight2 = getMinZoomScale() * getHeight() / 2.;
+		} else {
+			// ****************************************************************************
+			// Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen
+			// ****************************************************************************
+			newArea = env;
+		}
 
-			if (((Geometry) singleFeature.getDefaultGeometry())
-					.getCoordinates().length > 1) {
-				// System.out.println("Zoomed to only pne poylgon");
-				// Poly
-				// TODO max width vs. height
-				width = features.getBounds().getWidth() * 3;
-				height = ratio * width;
-			} else {
-				// System.out.println("Zoomed in a bit becasue only one point");
-				// width *= .9;
-				// height *= .9;
+		if (newArea == null) {
+
+			final Coordinate ll = new Coordinate(centerX - newWidth2, centerY
+					- newHeight2);
+			final Coordinate ur = new Coordinate(centerX + newWidth2, centerY
+					+ newHeight2);
+
+			newArea = new Envelope(ll, ur);
+		}
+
+		final Envelope maxAllowedExtend = getMaxExtend();
+		while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
+				&& newArea != null && !newArea.isNull()
+				&& !Double.isNaN(newArea.getMinX())
+				&& !Double.isNaN(newArea.getMaxX())
+				&& !Double.isNaN(newArea.getMinY())
+				&& !Double.isNaN(newArea.getMaxY())) {
+			/*
+			 * If a maxExtend is set, we have to honour that...
+			 */
+
+			// Exceeds top? Move down and maybe cut
+			if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
+				final double divY = newArea.getMaxY()
+						- maxAllowedExtend.getMaxY();
+				// LOGGER.debug("Moving area down by " + divY);
+
+				newArea = new Envelope(new Coordinate(newArea.getMinX(),
+						newArea.getMinY() - divY), new Coordinate(newArea
+						.getMaxX(), newArea.getMaxY() - divY));
+
+				if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
+					// LOGGER.debug("Now it exeeds the bottom border.. cut!");
+					// And cut the bottom if it moved out of the area
+					newArea = new Envelope(new Coordinate(newArea.getMinX(),
+							maxAllowedExtend.getMinY()), new Coordinate(newArea
+							.getMaxX(), newArea.getMaxY()));
+
+					// LOGGER.debug("and fix aspect ratio");
+
+					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
+							false);
+				}
 			}
 
-			Coordinate centre = features.getBounds().centre();
-			if (!mapCRS.equals(fCRS)) {
-				// only to calculations if the CRS differ
-				try {
-					MathTransform fToMap;
-					fToMap = CRS.findMathTransform(fCRS, mapCRS);
-					// centre is transformed to the mapCRS
-					centre = JTS.transform(centre, null, fToMap);
-				} catch (FactoryException e) {
-					LOGGER.error("Looking for a Math transform", e);
-				} catch (TransformException e) {
-					LOGGER.error("Looking for a Math transform", e);
+			// Exceeds bottom? Move up and maybe cut
+			if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
+				final double divY = newArea.getMinY()
+						- maxAllowedExtend.getMinY();
+				// LOGGER.debug("Moving area up by " + divY);
+
+				newArea = new Envelope(new Coordinate(newArea.getMinX(),
+						newArea.getMinY() - divY), new Coordinate(newArea
+						.getMaxX(), newArea.getMaxY() - divY));
+
+				if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
+					// LOGGER.debug("Now it exeeds the top border.. cut!");
+					// And cut the bottom if it moved out of the area
+					newArea = new Envelope(new Coordinate(newArea.getMinX(),
+							newArea.getMinY()), new Coordinate(newArea
+							.getMaxX(), maxAllowedExtend.getMaxY()));
+
+					// LOGGER.debug("and fix aspect ratio");
+
+					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
+							false);
 				}
 			}
 
-			Coordinate newLeftBottom = new Coordinate(centre.x - width / 2.,
-					centre.y - height / 2.);
-			Coordinate newTopRight = new Coordinate(centre.x + width / 2.,
-					centre.y + height / 2.);
+			// Exceeds to the right? move and maybe cut
+			if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
 
-			Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
+				// Move left..
+				final double divX = newArea.getMaxX()
+						- maxAllowedExtend.getMaxX();
+				// LOGGER.debug("Moving area left by " + divX);
 
-			setMapArea(newMapArea);
+				newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
+						newArea.getMinY()), new Coordinate(newArea.getMaxX()
+						- divX, newArea.getMaxY()));
 
-		} else {
-			ReferencedEnvelope fBounds = features.getBounds();
+				if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
+					// LOGGER.debug("Now it exeeds the left border.. cut!");
+					// And cut the left if it moved out of the area
+					newArea = new Envelope(new Coordinate(maxAllowedExtend
+							.getMinX(), newArea.getMinY()), new Coordinate(
+							newArea.getMaxX(), newArea.getMaxY()));
 
-			Envelope bounds;
-			if (!mapCRS.equals(fCRS)) {
-				bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);
-			} else {
-				bounds = fBounds;
+					// LOGGER.debug("and fix aspect ratio");
+
+					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
+							false);
+				}
 			}
-			// BB umrechnen von Layer-CRS in Map-CRS
 
-			// Expand a bit
-			bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
+			// Exceeds to the left? move and maybe cut
+			if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
 
-			setMapArea(bounds);
+				// Move right..
+				final double divX = newArea.getMinX()
+						- maxAllowedExtend.getMinX();
+				// LOGGER.debug("Moving area right by " + divX);
+
+				newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
+						newArea.getMinY()), new Coordinate(newArea.getMaxX()
+						- divX, newArea.getMaxY()));
+
+				if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
+					// LOGGER.debug("Now it exeeds the right border.. cut!");
+					// And cut the left if it moved out of the area
+					newArea = new Envelope(new Coordinate(newArea.getMinX(),
+							newArea.getMinY()), new Coordinate(maxAllowedExtend
+							.getMaxX(), newArea.getMaxY()));
+
+					// LOGGER.debug("and fix aspect ratio");
+
+					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
+							false);
+				}
+			}
 		}
-	}
 
-	private void setRendererHints(Map<Object, Object> rendererHints) {
-		this.rendererHints = rendererHints;
+		return newArea;
 	}
 
 	/**
-	 * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
-	 * {@link XMapPane} is visible and has bounds set.
+	 * Should be called when the {@link JMapPane} is not needed no more to help
+	 * the GarbageCollector
+	 * 
+	 * Removes all {@link JMapPaneListener}s that are registered
+	 * 
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	 *         Kr&uuml;ger</a>
 	 */
-	public boolean isWellDefined() {
+	public void dispose() {
+		if (isDisposed())
+			return;
 
-		try {
+		setPainting(false);
 
-			if (getContext() == null)
-				return false;
-			if (getContext().getLayerCount() <= 0)
-				return false;
-			if (getMapArea() == null)
-				return false;
-			if (getBounds().getWidth() == 0)
-				return false;
-			if (getBounds().getHeight() == 0)
-				return false;
-		} catch (Exception e) {
-			return false;
+		resizeTimer.stop();
+		startRenderThreadsTimer.stop();
+
+		disposed = true;
+
+		if (bgExecuter != null) {
+			bgExecuter.cancelTask();
+			bgExecuter.dispose();
 		}
-		return true;
-	}
 
-	/**
-	 * Default delay (milliseconds) before the map will be redrawn when resizing
-	 * the pane. This is to avoid flickering while drag-resizing.
-	 */
-	public static final int DEFAULT_RESIZING_PAINT_DELAY = 500; // delay in
-	// milliseconds
+		if (localExecuter != null) {
+			int i = 0;
+			localExecuter.cancelTask();
+			while (i++ < 10 && localExecuter.isRunning()) {
+				try {
+					Thread.sleep(200);
+				} catch (final InterruptedException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+			}
+			if (localExecuter.isRunning()) {
+				System.out
+						.println("BAD BAD BAD... still running the thread....");
+			}
+			localExecuter.dispose();
+		}
+		//
+		// if (bgImage != null) {
+		// bgImage = dispose(bgImage);
+		// bgImage = null;
+		// // LangUtil.gcTotal();
+		// }
+		//
+		// if (localImage != null) {
+		// localImage = dispose(localImage);
+		// localImage = null;
+		// // LangUtil.gcTotal();
+		// }
+		//
+		// if (finalImage != null) {
+		// finalImage = dispose(finalImage);
+		// finalImage = null;
+		// // LangUtil.gcTotal();
+		// }
+		//
+		// if (preFinalImage != null) {
+		// preFinalImage = dispose(preFinalImage);
+		// preFinalImage = null;
+		// }
+		disposeImages();
 
-	private Timer resizeTimer;
-	private int resizingPaintDelay;
-	/**
-	 * We store the old transform for a moment to use it for the
-	 * "quick scaled preview" in case of ZoomIn
-	 **/
-	protected AffineTransform oldScreenToWorld = null;
+		// LangUtil.gcTotal();
 
-	/**
-	 * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
-	 * MapPane-Funktion
-	 */
-	protected Cursor staticCursor = null;
+		// Alle mapPaneListener entfernen
+		mapPaneListeners.clear();
 
-	/**
-	 * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
-	 * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
-	 * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
-	 * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
-	 * {@code null} als Parameter uebergeben werden
-	 * 
-	 * @param cursor
-	 *            Cursor
-	 */
-	public void setStaticCursor(Cursor cursor) {
-		this.staticCursor = cursor;
-		if (cursor != null)
-			super.setCursor(cursor);
-	}
+		removeMouseMotionListener(zoomMapPaneMouseListener);
+		removeMouseListener(zoomMapPaneMouseListener);
 
-	/**
-	 * Liefert den statisch eingestellten Cursor, der unabhaengig von der
-	 * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
-	 * 
-	 * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
-	 *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
-	 */
-	public Cursor getStaticCursor() {
-		return this.staticCursor;
+		if (localContext != null)
+			getContext().clearLayerList();
+		if (bgContext != null)
+			getBgContext().clearLayerList();
+
+		removeAll();
 	}
 
 	/**
-	 * Abhaengig von selState wird der Cursor gesetzt
+	 * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
+	 * given point. All in screen coordinates.
 	 */
-	public void updateCursor() {
+	protected void drawRectangle(final Graphics graphics, final Point startPos,
+			final Point e) {
 
-		if (bgExecuter != null && bgExecuter.isRunning()
-				|| localExecuter != null && localExecuter.isRunning()) {
-			setCursor(WAIT_CURSOR);
+		if (!isWellDefined())
 			return;
-		} else {
-			// Allow one last rendering
-			if (repainterTimer.isRunning()) {
-				repainterTimer.stop();
-				updateFinalImage();
-				repaint();
-			}
-		}
 
-		// wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
-		// von der aktuellen Aktion
-		if (this.staticCursor != null) {
-			setCursor(staticCursor);
+		// undraw last box/draw new box
+		final int left = Math.min(startPos.x, e.x);
+		final int right = Math.max(startPos.x, e.x);
+		final int top = Math.max(startPos.y, e.y);
+		final int bottom = Math.min(startPos.y, e.y);
+		final int width = right - left;
+		final int height = top - bottom;
+
+		if (width == 0 && height == 0)
 			return;
-		}
-		if (getCursor() == SwingUtil.PANNING_CURSOR) {
-			// This cursor will reset itself
-			return;
-		}
 
-		// Je nach Aktion den Cursor umsetzen
-		switch (state) {
-		case SELECT_TOP:
-		case SELECT_ONE_FROM_TOP:
-		case SELECT_ALL:
-			setCursor(SwingUtil.CROSSHAIR_CURSOR);
-			break;
-		case ZOOM_IN:
-			setCursor(SwingUtil.ZOOMIN_CURSOR);
-			break;
-		case ZOOM_OUT:
-			setCursor(SwingUtil.ZOOMOUT_CURSOR);
-			break;
-		case PAN:
-			setCursor(SwingUtil.PAN_CURSOR);
-			break;
-		default:
-			setCursor(normalCursor);
-			break;
-		}
+		graphics.setXORMode(Color.WHITE);
+		graphics.drawRect(left, bottom, width, height);
 	}
 
-	//
-	// /**
-	// * Gibt den "normalen" Cursor zurueck. Dieser kann neben dem "pointer"
-	// auch
-	// * ein Sanduhr-Wartecursor sein.
-	// *
-	// * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	// * Kr&uuml;ger</a>
-	// */
-	// public Cursor getNormalCursor() {
-	// return normalCursor;
-	// }
-	//
-	// /**
-	// * Setzt den "normalen" Cursor. Dieser kann neben dem default "pointer"
-	// z.B.
-	// * auch ein Sanduhr-Wartecursor sein.
-	// *
-	// * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	// * Kr&uuml;ger</a>
-	// */
-	// public void setNormalCursor(Cursor normalCursor) {
-	// this.normalCursor = normalCursor;
-	// }
-
 	/**
-	 * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten
-	 * neu.
+	 * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
+	 * to give the user something to look at while we are rendering. Method
+	 * should be called after {@link #setMapArea(Envelope)} has been set to the
+	 * new mapArea and transform has been reset.<br>
+	 * 
+	 * @param g
+	 *            Graphics2D to paint the preview into
+	 * 
+	 * @param state
+	 *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
 	 */
-	protected void resetTransforms() {
-		if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)
-			return;
+	protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
 
-		// We store the last Transform
-		oldScreenToWorld = screenToWorld;
+		if (quickPreviewHint == 0)
+			return false;
 
-		this.screenToWorld = new AffineTransform(
-		// Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten
-				// nach rechts (Osten) hin groesser
-				// --> positive Verschiebung
-				getMapArea().getWidth() / getWidth(),
-				// keine Verzerrung
-				0.0, 0.0,
-				// Waehrend die Fenster-Koordinaten nach unten hin groesser
-				// werden,
-				// werden Latitude-Koordinaten nach Sueden hin keiner
-				// --> negative Verschiebung
-				-getMapArea().getHeight() / getHeight(),
-				// Die Longitude-Koordinaten werden nach Osten hin groesser
-				// --> obere linke Ecke des Fensters hat also den Minimalwert
-				getMapArea().getMinX(),
-				// Die Latitude-Koordinaten werden nach Norden hin groesser
-				// --> obere linke Ecke des Fensters hat also den Maximalwert
-				getMapArea().getMaxY());
+		graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+				RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
+		graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+				RenderingHints.VALUE_ANTIALIAS_OFF);
+		graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
+				RenderingHints.VALUE_RENDER_SPEED);
 
-		try {
-			this.worldToScreen = screenToWorld.createInverse();
-		} catch (NoninvertibleTransformException e) {
-			LOGGER.error(e);
-		}
-	}
+		if (oldMapArea == null)
+			return false;
 
-	/**
-	 * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
-	 * (lat/lon)
-	 */
-	protected AffineTransform screenToWorld = null;
+		final Rectangle visibleArea = getVisibleRect();
 
-	private AffineTransform worldToScreen;
+		// Calculate the oldMapArea in the current WindowCoordinates:
+		final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
+				oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
+						.getMaxY(), null);
 
-	/**
-	 * Listens to changes of the "local" {@link MapContext} and triggers
-	 * repaints where needed.
-	 */
-	private MapLayerListListener localContextListener = new MapLayerListListener() {
+		final int xx1 = (int) Math.round(oldMapWindow.getMinX());
+		final int yy1 = (int) Math.round(oldMapWindow.getMinY());
+		final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
+		final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
 
-		@Override
-		public void layerAdded(final MapLayerListEvent event) {
-			event.getLayer().addMapLayerListener(localMapLayerListener);
+		graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
+				(int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
+				(int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
+				getMapBackgroundColor(), null);
 
-//			System.out.println("added a layer context, now it'S "
-//					+ getContext().getLayerCount() + " layers");
-//			;
+		final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
+				- yy1);
 
-			localRenderer.setContext(getContext());
+		SwingUtil.clearAround(graphics, painedArea, visibleArea);
 
-			if (localContext.getLayers().length == 1) { // the first one
-				// if the Area of Interest is unset, the LayerBounds are used
-				if (!setMapArea(localContext.getAreaOfInterest()))
-					repaint();
+		addGadgets(graphics);
 
-				return;
-			}
+		quickPreviewHint = 0;
 
-			// We need to redraw, even in case that the mapArea didn't change
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
+		graphics.dispose();
 
-		}
+		// Something has been drawn
+		return true;
+	}
 
-		@Override
-		public void layerRemoved(final MapLayerListEvent event) {
-			if (event.getLayer() != null)
-				event.getLayer().removeMapLayerListener(localMapLayerListener);
-			// mapImageInvalid = true;
-			// repaint();
-			localRenderer.setContext(getContext());
-			requestStartRendering();
-		}
+	public MapContext getBgContext() {
+		return bgContext;
+	}
 
-		@Override
-		public void layerChanged(final MapLayerListEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			localRenderer.setContext(getContext());
-			requestStartRendering();
+	/**
+	 * Lazyly initializes a {@link BufferedImage} for the background renderer.
+	 */
+	private Image getBgImage() {
+		//
+		// if (bgImage == null) {
+		// bgImage = createImage(getBounds().width, getBounds().height);
+		// }
+
+		return bgImage;
+	}
+
+	public MapContext getContext() {
+		if (localContext == null) {
+			setLocalContext(new DefaultMapContext());
 		}
+		return localContext;
+	}
 
-		@Override
-		public void layerMoved(final MapLayerListEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			localRenderer.setContext(getContext());
+	private BufferedImage getFinalImage() {
+		//
+		if (finalImage == null) {
+			// Rectangle curPaintArea = getVisibleRect();
+			finalImage = new BufferedImage(getBounds().width,
+					getBounds().height, IMAGETYPE);
+
 			requestStartRendering();
 		}
-	};
+		return finalImage;
+	}
 
+	public RenderingHints getJava2dHints() {
+		return java2dHints;
+	}
+
 	/**
-	 * Listens to changes of the "background" {@link MapContext} and triggers
-	 * repaints where needed.
+	 * Lazyly initializes a {@link BufferedImage} for the background renderer.
 	 */
-	private MapLayerListListener bgContextListener = new MapLayerListListener() {
+	private BufferedImage getLocalImage() {
 
-		@Override
-		public void layerAdded(final MapLayerListEvent event) {
-			event.getLayer().addMapLayerListener(bgMapLayerListener);
+		if (localImage == null) {
+			localImage = new BufferedImage(getBounds().width,
+					getBounds().height, IMAGETYPE_withAlpha);
+		}
 
-			if (localContext.getLayers().length == 0
-					&& bgContext.getLayers().length == 1) { // the first one and
-				// localContext is
-				// empty
-				if (!setMapArea(localContext.getAreaOfInterest()))
-					requestStartRendering();
-				return;
+		return localImage;
+	}
+
+	/**
+	 * Returns a copy of the mapArea
+	 * 
+	 * @return
+	 */
+	public Envelope getMapArea() {
+		if (mapArea == null) {
+			ReferencedEnvelope mapArea_ = null;
+			try {
+				mapArea_ = localContext.getLayerBounds();
+			} catch (final IOException e) {
+				LOGGER.warn("context.getLayerBounds()", e);
 			}
 
-			// We need to redraw, even in case that the mapArea didn't change
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-
+			if (mapArea_ != null) {
+				mapImageInvalid = true; /* note we need to redraw */
+//				setMapArea(mapArea_); // results in a loop
+				mapArea = bestAllowedMapArea(mapArea_);
+			}
 		}
 
-		@Override
-		public void layerRemoved(final MapLayerListEvent event) {
-			if (event.getLayer() != null)
-				event.getLayer().removeMapLayerListener(bgMapLayerListener);
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
+		if (mapArea == null)
+			return null;
 
-		@Override
-		public void layerChanged(final MapLayerListEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
+		return new Envelope(mapArea);
+	}
 
-		@Override
-		public void layerMoved(final MapLayerListEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
-	};
+	/**
+	 * Returns the background {@link Color} of the map pane. Default is white.
+	 **/
+	public Color getMapBackgroundColor() {
+		return mapBackgroundColor;
+	}
 
 	/**
-	 * Listens to each layer in the local {@link MapContext} for changes and
-	 * triggers repaints.
+	 * Get the BufferedImage to use as a flaoting icon in the lower right
+	 * corner.
+	 * 
+	 * @return <code>null</code> if the feature is deactivated.
 	 */
-	protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
+	public BufferedImage getMapImage() {
+		return mapImage;
+	}
 
-		@Override
-		public void layerShown(MapLayerEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
+	/**
+	 * Returns the evelope of the viewable area. The JMapPane will never show
+	 * anything outside of this extend. If this has been set to
+	 * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return
+	 * quickly the context's bounds. It it takes to long to determine the
+	 * context bounds, <code>null</code> is returned.
+	 * 
+	 * @param maxExtend
+	 *            <code>null</code> to not have this restriction.
+	 */
 
-		@Override
-		public void layerHidden(MapLayerEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
+	public Envelope getMaxExtend() {
+		if (maxExtend == null) {
+			final ReferencedEnvelope layerBounds = GTUtil
+					.getVisibleLayoutBounds(localContext);
+			if (layerBounds == null) {
+				// TODO Last fallback could be the CRS valid area
+				return null;
+			}
 
-		@Override
-		public void layerChanged(MapLayerEvent event) {
-			localRenderer.setContext(getContext()); // betters for SLD changes?!
-			// Change of SLD for example
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
+			// Kartenbereich um 10% vergroessern
+			return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil
+					.expandEnvelope(layerBounds, 0.1), true);
 		}
-	};
+		return maxExtend;
+	}
 
 	/**
-	 * Listens to each layer in the local {@link MapContext} for changes and
-	 * triggers repaints.
+	 * Retuns the maximum allowed zoom scale. This is the smaller number value
+	 * of the two. Defaults to {@link Double}.MIN_VALUE
+	 * 
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	 *         Kr&uuml;ger</a>
 	 */
-	protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
+	public Double getMaxZoomScale() {
+		return maxZoomScale;
+	}
 
-		@Override
-		public void layerShown(MapLayerEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
+	/**
+	 * Retuns the minimum allowed zoom scale. This is the bigger number value of
+	 * the two. Defaults to {@link Double}.MAX_VALUE
+	 * 
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	 *         Kr&uuml;ger</a>
+	 */
+	public Double getMinZoomScale() {
+		return minZoomScale;
+	}
 
-		@Override
-		public void layerHidden(MapLayerEvent event) {
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
+	private Image getPreFinalImage() {
+		// if (preFinalImage == null) {
+		//			
+		// // Rectangle curPaintArea = getVisibleRect();
+		// // preFinalImage = new BufferedImage(curPaintArea.width,
+		// // curPaintArea.height, BufferedImage.TYPE_INT_RGB);
+		//			
+		// preFinalImage = createImage(getBounds().width, getBounds().height);
+		//
+		// requestStartRendering();
+		// }
+		return preFinalImage;
+	}
 
-		@Override
-		public void layerChanged(MapLayerEvent event) {
-			// Change of SLD for example
-			// mapImageInvalid = true;
-			// repaint();
-			requestStartRendering();
-		}
-	};
+	public Map<Object, Object> getRendererHints() {
+		return rendererHints;
+	}
 
 	/**
 	 * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
@@ -907,6 +1216,21 @@
 		return new AffineTransform(screenToWorld);
 	}
 
+	public int getState() {
+		return state;
+	}
+
+	/**
+	 * Liefert den statisch eingestellten Cursor, der unabhaengig von der
+	 * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
+	 * 
+	 * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
+	 *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
+	 */
+	public Cursor getStaticCursor() {
+		return this.staticCursor;
+	}
+
 	public AffineTransform getWorldToScreenTransform() {
 		if (worldToScreen == null) {
 			resetTransforms();
@@ -915,52 +1239,382 @@
 		return new AffineTransform(worldToScreen);
 	}
 
-	public MapContext getContext() {
-		if (localContext == null) {
-			setLocalContext(new DefaultMapContext());
+	/**
+	 * A flag indicating if dispose() has already been called. If true, then
+	 * further use of this {@link SelectableXMapPane} is undefined.
+	 */
+	private boolean isDisposed() {
+		return disposed;
+	}
+
+	/**
+	 * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
+	 * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns
+	 * <code>true</code> if the selectability has not been defined.
+	 * 
+	 * @param layer
+	 *            a layer
+	 */
+	public boolean isMapLayerSelectable(final MapLayer layer) {
+		final Boolean selectable = mapLayerSelectable.get(layer);
+		return selectable == null ? true : selectable;
+	}
+
+	/**
+	 * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
+	 * {@link XMapPane} is visible and has bounds set.
+	 */
+	public boolean isWellDefined() {
+
+		try {
+
+			if (getContext() == null)
+				return false;
+			if (getContext().getLayerCount() <= 0)
+				return false;
+			if (getMapArea() == null)
+				return false;
+			if (getBounds().getWidth() == 0)
+				return false;
+			if (getBounds().getHeight() == 0)
+				return false;
+		} catch (final Exception e) {
+			return false;
 		}
-		return localContext;
+		return true;
 	}
 
-	public MapContext getBgContext() {
-		return bgContext;
+	public void mouseDragged(final Point startPos, final Point lastPos,
+			final MouseEvent event) {
+
+		if ((getState() == XMapPane.PAN)
+				|| ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
+
+			if (getCursor() != SwingUtil.PANNING_CURSOR) {
+				setCursor(SwingUtil.PANNING_CURSOR);
+
+				// While panning, we deactivate the rendering. So the tasts are
+				// ready to start when the panning os done.
+				if (bgExecuter != null)
+					bgExecuter.cancelTask();
+				if (localExecuter != null)
+					localExecuter.cancelTask();
+			}
+
+			if (lastPos.x > 0 && lastPos.y > 0) {
+				final int dx = event.getX() - lastPos.x;
+				final int dy = event.getY() - lastPos.y;
+
+				// TODO Stop dragging when the drag would not be valid...
+				// boolean dragValid = true;
+				// // check if this panning results in a valid mapArea
+				// {
+				// Rectangle winBounds = xMapPane.getBounds();
+				// winBounds.translate(xMapPane.imageOrigin.x,
+				// -xMapPane.imageOrigin.y);
+				// Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
+				// winBounds.x, winBounds.y, winBounds.x
+				// + winBounds.width, winBounds.y
+				// + winBounds.height);
+				//					
+				//
+				// winBounds = xMapPane.getBounds();
+				// Point testIng = new Point(xMapPane.imageOrigin);
+				// testIng.translate(dx, dy);
+				// winBounds.translate(testIng.x, -testIng.y);
+				// Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
+				// winBounds.x, winBounds.y, winBounds.x
+				// + winBounds.width, winBounds.y
+				// + winBounds.height);
+				//
+				// // If the last drag doesn't change the MapArea anymore cancel
+				// it.
+				// if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
+				// xMapPane.bestAllowedMapArea(newMapAreaBefore))){
+				// dragValid = false;
+				// return;
+				// }
+				// }
+
+				imageOrigin.translate(dx, dy);
+				updateFinalImage();
+				repaint();
+			}
+
+		} else if ((getState() == XMapPane.ZOOM_IN)
+				|| (getState() == XMapPane.ZOOM_OUT)
+				|| (getState() == XMapPane.SELECT_ALL)
+				|| (getState() == XMapPane.SELECT_TOP)
+		// || (getState() == XMapPane.SELECT_ONE_FROM_TOP)
+		) {
+			final Graphics graphics = getGraphics();
+
+			drawRectangle(graphics, startPos, event.getPoint());
+
+			if ((lastPos.x > 0) && (lastPos.y > 0)) {
+				drawRectangle(graphics, startPos, lastPos);
+			}
+
+			graphics.dispose();
+
+		}
+
 	}
 
 	/**
+	 * Called by the {@link RenderingExecutor} when rendering was cancelled.
+	 */
+	public void onRenderingCancelled() {
+		repaintTimer.stop();
+		LOGGER.debug("Rendering cancelled");
+	}
+
+	/**
+	 * Called by the {@link RenderingExecutor} when rendering has been
+	 * completed.
+	 */
+	public void onRenderingCompleted() {
+		repaintTimer.stop();
+		updateFinalImage();
+		repaint();
+	}
+
+	/**
+	 * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
+	 * Publishes a {@linkplain MapPaneEvent} of type {@code
+	 * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
 	 * 
-	 * @param context
+	 * @param renderingError
+	 *            The error that occured during rendering
+	 * 
+	 * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
 	 */
-	public void setLocalContext(final MapContext context) {
-		// Remove the default listener from the old context
-		if (this.localContext != null) {
-			this.localContext.removeMapLayerListListener(localContextListener);
+	public void onRenderingFailed(final Exception renderingError) {
+		repaintTimer.stop();
+		LOGGER.warn("Rendering failed", renderingError);
+		updateFinalImage();
+		repaint();
 
-			// adding listener to all layers
-			for (MapLayer mapLayer : localContext.getLayers()) {
-				mapLayer.removeMapLayerListener(localMapLayerListener);
+	}
+
+	public void onRenderingPending() {
+		// LOGGER.debug("Pending rendering updates the preview...");
+		updateFinalImage();
+		repaint();
+	}
+
+	@Override
+	protected void paintComponent(final Graphics g) {
+		if (!acceptsRepaintCalls)
+			return;
+
+		// Maybe update the cursor and maybe stop the repainting timer
+		updateCursor();
+
+		super.paintComponent(g); // candidate for removal
+
+		boolean paintedSomething = false;
+
+		if (mapImageInvalid) { /* if the map changed then redraw */
+
+			mapImageInvalid = false; // Reset for next round
+
+			// If the new mapArea and the oldMapArea intersect, we can draw some
+			// quick scaled preview to make the user feel that something is
+			// happening.
+			if (mapAreaChanged && oldMapArea != null
+					&& getMapArea().intersects(oldMapArea)
+					& !getMapArea().equals(oldMapArea)) {
+
+				mapAreaChanged = false;
+
+				if (getMapArea().covers(oldMapArea)) {
+					setQuickPreviewHint(ZOOM_OUT);
+					paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
+				} else if (oldMapArea.covers(getMapArea())) {
+					setQuickPreviewHint(ZOOM_IN);
+					paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
+				}
+
 			}
+
+			if (paneResized) {
+				paneResized = false;
+				disposeImages();
+			}
+
+			// Start the Threads and Timers to render the image
+			requestStartRendering();
+
 		}
 
-		this.localContext = context;
+		if (!paintedSomething) {
 
-		if (context != null) {
+			g.drawImage(getFinalImage(), 0, 0, null);
 
-			setMapArea(localContext.getAreaOfInterest());
+			g.dispose(); // cand. for removal
 
-			localRenderer.setContext(localContext);
+			paintedSomething = true; // cand. for removal
+		}
 
-			this.localContext.addMapLayerListListener(localContextListener);
+	}
 
-			// adding listener to all layers
-			for (MapLayer mapLayer : localContext.getLayers()) {
-				mapLayer.addMapLayerListener(localMapLayerListener);
-			}
+	/**
+	 * Heavily works on releasing all resources related to the four
+	 * {@link Image}s used to cache the results of the different renderers.<br>
+	 * In November 2009 i had some memory leaking problems with {@link XMapPane}
+	 * . The resources of the buffered images were never released. It seem to be
+	 * important to call the GC right after flushing the images.<br>
+	 * Hence this method may take a while, because it calls the GC up to four
+	 * times.
+	 */
+	private void disposeImages() {
+
+		// System.out.println("vorher = "
+		// + new MbDecimalFormatter().format(LangUtil.gcTotal()));
+		// bi.flush();
+		// return bi = null;
+		// System.out.println("nacher = "
+		// + new MbDecimalFormatter().format(LangUtil.gcTotal()));
+		//
+		// System.out.println("\n");
+
+		if (preFinalImage != null) {
+			preFinalImage.flush();
+			preFinalImage = null;
+			LangUtil.gc();
 		}
+		if (finalImage != null) {
+			finalImage.flush();
+			finalImage = null;
+			LangUtil.gc();
+		}
+		if (localImage != null) {
+			localImage.flush();
+			localImage = null;
+			LangUtil.gc();
+		}
+		if (bgImage != null) {
+			bgImage.flush();
+			bgImage = null;
+			LangUtil.gc();
+		}
 
-		mapImageInvalid = true;
-		repaint();
 	}
 
+	/**
+	 * Performs a {@value #PAN} action. During panning, the displacement is
+	 * stored in {@link #imageOrigin} object. Calling {@link #performPan()} will
+	 * reset the offset and call {@link #setMapArea(Envelope)}.
+	 */
+	public void performPan() {
+
+		final Rectangle winBounds = getBounds();
+		winBounds.translate(-imageOrigin.x, -imageOrigin.y);
+		final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
+				winBounds.y, winBounds.x + winBounds.width, winBounds.y
+						+ winBounds.height);
+
+		imageOrigin.x = 0;
+		imageOrigin.y = 0;
+
+		if (!setMapArea(newMapArea)) {
+			/**
+			 * If setMapArea returns true, the finalImage is updated anyways.
+			 * This if-case exists to ensure that we repaint a correct image
+			 * even if the new panning area has been denied.
+			 */
+			updateFinalImage();
+			repaint();
+		}
+
+		if (getCursor() == SwingUtil.PANNING_CURSOR)
+			setCursor(SwingUtil.PAN_CURSOR);
+	}
+
+	//
+	// /**
+	// * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot
+	// gemacht
+	// * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.
+	// *
+	// * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	// * Kr&uuml;ger</a>
+	// */
+	// @Override
+	// public void print(final Graphics g) {
+	// final Color orig = getBackground();
+	// setBackground(Color.WHITE);
+	//
+	// // wrap in try/finally so that we always restore the state
+	// try {
+	// super.print(g);
+	// } finally {
+	// setBackground(orig);
+	// }
+	// }
+
+	/**
+	 * Entfernt einen Listener von der Map.
+	 * 
+	 * @param l
+	 *            zu entfernender Listener
+	 */
+	public void removeMapPaneListener(final JMapPaneListener l) {
+		mapPaneListeners.remove(l);
+	}
+
+	/**
+	 * Cancels all running renderers and sets the flag to start new ones. <br>
+	 * 
+	 * @see #startRenderThreadsTimer
+	 */
+	private void requestStartRendering() {
+		if (bgExecuter != null)
+			bgExecuter.cancelTask();
+		if (localExecuter != null)
+			localExecuter.cancelTask();
+		requestStartRendering = true;
+
+	}
+
+	/**
+	 * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten
+	 * neu.
+	 */
+	protected void resetTransforms() {
+		if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)
+			return;
+
+		// We store the last Transform
+		oldScreenToWorld = screenToWorld;
+
+		this.screenToWorld = new AffineTransform(
+		// Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten
+				// nach rechts (Osten) hin groesser
+				// --> positive Verschiebung
+				getMapArea().getWidth() / getWidth(),
+				// keine Verzerrung
+				0.0, 0.0,
+				// Waehrend die Fenster-Koordinaten nach unten hin groesser
+				// werden,
+				// werden Latitude-Koordinaten nach Sueden hin keiner
+				// --> negative Verschiebung
+				-getMapArea().getHeight() / getHeight(),
+				// Die Longitude-Koordinaten werden nach Osten hin groesser
+				// --> obere linke Ecke des Fensters hat also den Minimalwert
+				getMapArea().getMinX(),
+				// Die Latitude-Koordinaten werden nach Norden hin groesser
+				// --> obere linke Ecke des Fensters hat also den Maximalwert
+				getMapArea().getMaxY());
+
+		try {
+			this.worldToScreen = screenToWorld.createInverse();
+		} catch (final NoninvertibleTransformException e) {
+			LOGGER.error(e);
+		}
+	}
+
 	public void setBgContext(final MapContext context) {
 
 		// Remove the default listener from the old context
@@ -968,7 +1622,7 @@
 			this.bgContext.removeMapLayerListListener(bgContextListener);
 
 			// adding listener to all layers
-			for (MapLayer mapLayer : bgContext.getLayers()) {
+			for (final MapLayer mapLayer : bgContext.getLayers()) {
 				mapLayer.removeMapLayerListener(bgMapLayerListener);
 			}
 		}
@@ -981,7 +1635,7 @@
 			this.bgContext.addMapLayerListListener(bgContextListener);
 
 			// adding listener to all layers
-			for (MapLayer mapLayer : bgContext.getLayers()) {
+			for (final MapLayer mapLayer : bgContext.getLayers()) {
 				mapLayer.addMapLayerListener(bgMapLayerListener);
 			}
 		}
@@ -989,30 +1643,43 @@
 		repaint();
 	}
 
+	public void setJava2dHints(final RenderingHints java2dHints) {
+		this.java2dHints = java2dHints;
+	}
+
 	/**
-	 * Returns a copy of the mapArea
 	 * 
-	 * @return
+	 * @param context
 	 */
-	public Envelope getMapArea() {
-		if (mapArea == null) {
-			ReferencedEnvelope mapArea_ = null;
-			try {
-				mapArea_ = localContext.getLayerBounds();
-			} catch (final IOException e) {
-				LOGGER.warn("context.getLayerBounds()", e);
+	public void setLocalContext(final MapContext context) {
+		// Remove the default listener from the old context
+		if (this.localContext != null) {
+			this.localContext.removeMapLayerListListener(localContextListener);
+
+			// adding listener to all layers
+			for (final MapLayer mapLayer : localContext.getLayers()) {
+				mapLayer.removeMapLayerListener(localMapLayerListener);
 			}
+		}
 
-			if (mapArea_ != null) {
-				mapImageInvalid = true; /* note we need to redraw */
-				setMapArea(mapArea_);
+		this.localContext = context;
+
+		if (context != null) {
+
+			setMapArea(localContext.getAreaOfInterest());
+
+			localRenderer.setContext(localContext);
+
+			this.localContext.addMapLayerListListener(localContextListener);
+
+			// adding listener to all layers
+			for (final MapLayer mapLayer : localContext.getLayers()) {
+				mapLayer.addMapLayerListener(localMapLayerListener);
 			}
 		}
 
-		if (mapArea == null)
-			return null;
-
-		return new Envelope(mapArea);
+		mapImageInvalid = true;
+		repaint();
 	}
 
 	/**
@@ -1041,9 +1708,9 @@
 
 		// Testing, whether the difference if just minimal
 		if (mapArea != null) {
-			Envelope candNew = bestAllowedMapArea(newMapArea);
-			double tolX = mapArea.getWidth() / 1000.;
-			double tolY = mapArea.getHeight() / 1000.;
+			final Envelope candNew = bestAllowedMapArea(newMapArea);
+			final double tolX = mapArea.getWidth() / 1000.;
+			final double tolY = mapArea.getHeight() / 1000.;
 			if ((candNew.getMinX() - tolX < mapArea.getMinX())
 					&& (mapArea.getMinX() < candNew.getMinX() + tolX)
 					&& (candNew.getMaxX() - tolX < mapArea.getMaxX())
@@ -1082,368 +1749,147 @@
 		return true;
 	}
 
-	public int getState() {
-		return state;
-	}
-
 	/**
-	 * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
-	 * repaint Timer if
+	 * Set the background color of the map.
 	 * 
-	 * @param state
+	 * @param if <code>null</code>, white is used.
 	 */
-	public void setState(final int state) {
-		this.state = state;
-
-		zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
-				|| state == ZOOM_OUT || state == PAN));
-
-		// Je nach Aktion den Cursor umsetzen
-		updateCursor();
+	public void setMapBackgroundColor(Color bgColor) {
+		if (bgColor == null)
+			bgColor = Color.WHITE;
+		this.mapBackgroundColor = bgColor;
 	}
 
-	/** Cursor wenn kein Mausbutton gedrueckt wird. default oder SwingUtil.PAN **/
-	protected static Cursor normalCursor = Cursor
-			.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
-
-	public static final Cursor WAIT_CURSOR = Cursor
-			.getPredefinedCursor(Cursor.WAIT_CURSOR);
-
-	public static final int NONE = -123;
-
-	private RenderingExecutor localExecuter = new RenderingExecutor(this);
-
 	/**
-	 * A flag set it {@link #setMapArea(Envelope)} to indicated the
-	 * {@link #paintComponent(Graphics)} method, that the image on-screen is
-	 * associated with {@link #oldMapArea} and may hence be scaled for a quick
-	 * preview.<br/>
-	 * The flag is reset
-	 **/
-	private boolean mapAreaChanged = false;
-
-	private volatile Boolean requestStartRendering = false;
-
-	/**
-	 * The Renderer for the Background uses this Image. When set to null, please
-	 * dispose the {@link Graphics2D}
+	 * Set the BufferedImage to use as a flaoting icon in the lower right corner
+	 * 
+	 * @param mapImageIcon
+	 *            <code>null</code> is allowed and deactivates this icon.
 	 */
-	private BufferedImage bgImage;// = new
-	// BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);
+	public void setMapImage(final BufferedImage mapImage) {
+		this.mapImage = mapImage;
+	}
 
-	private BufferedImage finalImage;
-
 	/**
-	 * The Renderer for the LocalLayers uses this Image. When set to null,
-	 * please dispose this {@link Graphics2D}
+	 * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
+	 * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
+	 * 
+	 * @param layer
+	 *            a layer
+	 * @param selectable
+	 *            if {@code false} the layer is ignored during the upper
+	 *            mentioned actions. If <code>null</code>, the default (true)
+	 *            will be used.
 	 */
-	private BufferedImage localImage;// = new
-	// BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);
-	private BufferedImage preFinalImage;// = new
-
-	// BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);
-
-	protected void paintComponent(final Graphics g) {
-		if (!acceptsRepaintCalls)
-			return;
-		
-		// Maybe update the cursor
-		updateCursor();
-		
-		super.paintComponent(g);
-
-		boolean paintedSomething = false;
-
-		if (mapImageInvalid) { /* if the map changed then redraw */
-
-			mapImageInvalid = false; // Reset for next round
-
-			// If the new mapArea and the oldMapArea intersect, we can draw some
-			// quick scaled preview to make the user feel that something is
-			// happening.
-			if (mapAreaChanged && oldMapArea != null
-					&& getMapArea().intersects(oldMapArea)
-					& !getMapArea().equals(oldMapArea)) {
-
-				mapAreaChanged = false;
-
-				if (getMapArea().covers(oldMapArea)) {
-					setQuickPreviewHint(ZOOM_OUT);
-					paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
-				} else if (oldMapArea.covers(getMapArea())) {
-					setQuickPreviewHint(ZOOM_IN);
-					paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
-				}
-
-			}
-
-			if (paneResized) {
-				paneResized = false;
-
-				// if (preFinalImage != null)
-				// preFinalImage.flush();
-				// preFinalImage = null;
-				// if (finalImage != null) {
-				// finalImage.flush();
-				// }
-				// finalImage = null;
-				// if (localImage != null)
-				// localImage.flush();
-				// localImage = null;
-				// if (bgImage != null)
-				// bgImage.flush();
-				// bgImage = null;
-
-				// gadgetsImage = null;
-			}
-
-			// Start the Threads and Timers to render the image
-			requestStartRendering();
-
-		}
-
-		if (!paintedSomething) {
-
-			// TODO Should just paint the getFinalImage(). Update should be
-			// called by timer every 300ms, and the repaint() until all threads
-			// are done.
-			g.drawImage(getFinalImage(), 0, 0, null);
-
-			g.dispose();
-
-			paintedSomething = true;
-		}
-
+	public void setMapLayerSelectable(final MapLayer layer,
+			final Boolean selectable) {
+		if (selectable == null)
+			mapLayerSelectable.remove(layer);
+		else
+			mapLayerSelectable.put(layer, selectable);
 	}
 
 	/**
-	 * Cancels all running renderers and sets the flag to start new ones. <br/>
+	 * Defines an evelope of the viwable area. The JMapPane will never show
+	 * anything outside of this extend.
 	 * 
-	 * @see #startRenderThreadsTimer
+	 * @param maxExtend
+	 *            <code>null</code> to not have this restriction.
 	 */
-	private void requestStartRendering() {
-		if (bgExecuter != null)
-			bgExecuter.cancelTask();
-		if (localExecuter != null)
-			localExecuter.cancelTask();
-		requestStartRendering = true;
-
+	public void setMaxExtend(final Envelope maxExtend) {
+		this.maxExtend = maxExtend;
 	}
 
 	/**
-	 * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
+	 * Set the maximum allowed zoom scale. This is the smaller number value of
+	 * the two. If <code>null</code> is passed, Double.MINVALUE are used which
+	 * mean there is no restriction.
 	 * 
-	 * @param ox
-	 *            X-Koordinate der VON-Position
-	 * @param oy
-	 *            Y-Koordinate der VON-Position
-	 * @param px
-	 *            X-Koordinate der BIS-Position
-	 * @param py
-	 *            Y-Koordinate der BIS-Position
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	 *         Kr&uuml;ger</a>
 	 */
-	public Envelope tranformWindowToGeo(int ox, int oy, int px, int py) {
-		AffineTransform at = getScreenToWorld();
-		Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
-		Point2D geoP = at.transform(new Point2D.Double(px, py), null);
-		return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
+	public void setMaxZoomScale(final Double maxZoomScale) {
+		this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
+				: maxZoomScale;
 	}
 
+	// /** Stored the time used for the last real rendering in ms. **/
+	// private long lastRenderingDuration = Long.MAX_VALUE;
+
 	/**
-	 * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
+	 * Set the minimum (nearest) allowed zoom scale. This is the bigger number
+	 * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
+	 * used which mean there is no restriction.
 	 * 
-	 * @param ox
-	 *            X-Koordinate der VON-Position
-	 * @param oy
-	 *            Y-Koordinate der VON-Position
-	 * @param px
-	 *            X-Koordinate der BIS-Position
-	 * @param py
-	 *            Y-Koordinate der BIS-Position
-	 * @param winToGeotransform
-	 *            Eine Window to Geo transform. If <code>null</code>,
-	 *            {@link #getScreenToWorld()} is used.
+	 * 
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
+	 *         Kr&uuml;ger</a>
 	 */
-	public Envelope tranformGeoToWindow(double ox, double oy, double px,
-			double py, AffineTransform winToGeotransform) {
-		AffineTransform at = winToGeotransform == null ? getScreenToWorld()
-				: winToGeotransform;
-		Point2D geoO;
-		try {
-			geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);
-			Point2D geoP = at
-					.inverseTransform(new Point2D.Double(px, py), null);
-			return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP
-					.getY());
-		} catch (NoninvertibleTransformException e) {
-			LOGGER.error(e);
-			return new Envelope(ox, oy, px, py);
-		}
+	public void setMinZoomScale(final Double minZoomScale) {
+		this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
+				: minZoomScale;
 	}
 
 	/**
-	 * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
-	 * to give the user something to look at while we are rendering. Method
-	 * should be called after {@link #setMapArea(Envelope)} has been set to the
-	 * new mapArea and transform has been reset.<br/>
 	 * 
-	 * @param g
-	 *            Graphics2D to paint the preview into
-	 * 
-	 * @param state
-	 *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
+	 * @param b
 	 */
-	protected boolean drawScaledPreviewImage_Zoom(Graphics2D graphics) {
+	public void setPainting(final boolean b) {
+		acceptsRepaintCalls = b;
+	}
 
-		if (quickPreviewHint == 0)
-			return false;
+	// /**
+	// * Returns in milli seconds the time the last rending of the
+	// * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has
+	// not
+	// * been rendered yet.
+	// */
+	// public long getLastRenderingDuration() {
+	// return lastRenderingDuration;
+	// }
 
-		graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
-				RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
-		graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
-				RenderingHints.VALUE_ANTIALIAS_OFF);
-		graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
-				RenderingHints.VALUE_RENDER_SPEED);
+	public void setQuickPreviewHint(final int quickPreviewHint) {
+		this.quickPreviewHint = quickPreviewHint;
 
-		if (oldMapArea == null)
-			return false;
+	}
 
-		Rectangle visibleArea = getVisibleRect();
-
-		// Calculate the oldMapArea in the current WindowCoordinates:
-		Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
-				oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
-						.getMaxY(), null);
-
-		int xx1 = (int) Math.round(oldMapWindow.getMinX());
-		int yy1 = (int) Math.round(oldMapWindow.getMinY());
-		int xx2 = (int) Math.round(oldMapWindow.getMaxX());
-		int yy2 = (int) Math.round(oldMapWindow.getMaxY());
-
-		graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
-				(int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
-				(int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
-				getMapBackgroundColor(), null);
-
-		Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2 - yy1);
-
-		SwingUtil.clearAround(graphics, painedArea, visibleArea);
-
-		addGadgets(graphics);
-
-		quickPreviewHint = 0;
-
-		graphics.dispose();
-
-		// Something has been drawn
-		return true;
+	private void setRendererHints(final Map<Object, Object> rendererHints) {
+		this.rendererHints = rendererHints;
 	}
 
-	final static Font waitFont = new Font("Arial", Font.BOLD, 30);
-
 	/**
-	 * Paints some optinal stuff into the given {@link Graphics2D}. Usually
-	 * called as the last paint on the mapImage.
+	 * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
+	 * repaint Timer if
+	 * 
+	 * @param state
 	 */
-	private void addGadgets(Graphics2D graphics) {
+	public void setState(final int state) {
+		this.state = state;
 
-		if (mapImage != null)
-			graphics.drawImage(mapImage, getBounds().width
-					- mapImage.getWidth() - 10, getBounds().height
-					- mapImage.getHeight() - 10, null);
+		zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
+				|| state == ZOOM_OUT || state == PAN));
 
-		// If still rendering, paint a gray shadow or so...
-		if (bgExecuter != null && bgExecuter.isRunning()
-				|| localExecuter != null && localExecuter.isRunning()) {
-
-			Color c = graphics.getColor();
-			graphics.setColor(Color.BLACK);
-
-			graphics.setFont(waitFont);
-			graphics.drawString("Wait...", 40, 70); // i8n
-
-			graphics.setColor(c);
-		}
-
+		// Je nach Aktion den Cursor umsetzen
+		updateCursor();
 	}
 
 	/**
-	 * Accumulates all three images
+	 * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
+	 * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
+	 * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
+	 * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
+	 * {@code null} als Parameter uebergeben werden
 	 * 
-	 * @return
+	 * @param cursor
+	 *            Cursor
 	 */
-	synchronized protected Image updateFinalImage() {
-
-		// Render the two map images first, into the preFinalImage
-		if (bgExecuter != null) {
-			final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
-					.getGraphics();
-			preFinalG.setBackground(getMapBackgroundColor());
-
-			preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
-					null);
-
-			// // Draw the local layers image
-			preFinalG.drawImage(getLocalImage(), 0, 0, null);
-			preFinalG.dispose();
-
-		} else {
-			preFinalImage = getLocalImage();
-		}
-
-		final Graphics2D finalG = getFinalImage().createGraphics();
-		finalG.setBackground(getMapBackgroundColor());
-		finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
-				getMapBackgroundColor(), null);
-
-		final int finalImageHeight = getFinalImage().getHeight(null);
-		final int finalImageWidth = getFinalImage().getWidth(null);
-
-		Rectangle painedArea = new Rectangle(imageOrigin.x, imageOrigin.y,
-				finalImageWidth, finalImageHeight);
-		SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
-
-		addGadgets(finalG);
-
-		finalG.dispose();
-
-		return finalImage;
+	public void setStaticCursor(final Cursor cursor) {
+		this.staticCursor = cursor;
+		if (cursor != null)
+			super.setCursor(cursor);
 	}
 
-	private BufferedImage getFinalImage() {
-		//
-		if (finalImage == null) {
-			// Rectangle curPaintArea = getVisibleRect();
-			finalImage = new BufferedImage(getBounds().width,
-					getBounds().height, BufferedImage.TYPE_INT_RGB);
-
-			requestStartRendering();
-		}
-		return finalImage;
-	}
-
-	private Image getPreFinalImage() {
-		// if (preFinalImage == null) {
-		//			
-		// // Rectangle curPaintArea = getVisibleRect();
-		// // preFinalImage = new BufferedImage(curPaintArea.width,
-		// // curPaintArea.height, BufferedImage.TYPE_INT_RGB);
-		//			
-		// preFinalImage = createImage(getBounds().width, getBounds().height);
-		//
-		// requestStartRendering();
-		// }
-		return preFinalImage;
-	}
-
 	/**
-	 * While dragging, the {@link #updateFinalImage()} method is translating the
-	 * cached images while setting it together.
-	 **/
-	Point imageOrigin = new Point(0, 0);
-	private final GTRenderer localRenderer;
-
-	/**
 	 * Starts rendering on one or two threads
 	 */
 	private void startRendering() {
@@ -1460,9 +1906,8 @@
 			localExecuter.cancelTask();
 		}
 
-		Rectangle curPaintArea = getVisibleRect();
+		final Rectangle curPaintArea = getVisibleRect();
 
-
 		/**
 		 * We have to set new renderer
 		 */
@@ -1481,575 +1926,305 @@
 
 		if (getContext() != null) {
 			// localExecuter = new RenderingExecutor(this, 150l);
-//			LOGGER.debug("starting local renderer:");
-			
+			// LOGGER.debug("starting local renderer:");
+
 			// Clear label cache
 			labelCache.clear();
-			Map<Object, Object> rh = localRenderer.getRendererHints();
+			final Map<Object, Object> rh = localRenderer.getRendererHints();
 			rh.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
 			localRenderer.setRendererHints(rh);
 
-			boolean submitted = localExecuter.submit(getContext().getAreaOfInterest(),
-					curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
-					localRenderer, getWorldToScreenTransform());
-			if (submitted) repainterTimer.restart();
-			else requestStartRendering = true; // Try to start rendering again in a moment
+			final boolean submitted = localExecuter.submit(getContext()
+					.getAreaOfInterest(), curPaintArea,
+					(Graphics2D) getLocalImage().getGraphics(), localRenderer,
+					getWorldToScreenTransform());
+			if (submitted)
+				repaintTimer.restart();
+			else
+				requestStartRendering = true; // Try to start rendering again in
+			// a moment
 		}
 
 		updateCursor();
-
 	}
 
 	/**
-	 * Lazyly initializes a {@link BufferedImage} for the background renderer.
-	 */
-	private Image getBgImage() {
-		//
-		// if (bgImage == null) {
-		// bgImage = createImage(getBounds().width, getBounds().height);
-		// }
-
-		return bgImage;
-	}
-
-	/** An (transparent) image to paint over the map in the lower right corner **/
-	private BufferedImage mapImage = null;
-
-	private boolean acceptsRepaintCalls = true;
-
-	/**
-	 * Get the BufferedImage to use as a flaoting icon in the lower right
-	 * corner.
+	 * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
 	 * 
-	 * @return <code>null</code> if the feature is deactivated.
+	 * @param ox
+	 *            X-Koordinate der VON-Position
+	 * @param oy
+	 *            Y-Koordinate der VON-Position
+	 * @param px
+	 *            X-Koordinate der BIS-Position
+	 * @param py
+	 *            Y-Koordinate der BIS-Position
+	 * @param winToGeotransform
+	 *            Eine Window to Geo transform. If <code>null</code>,
+	 *            {@link #getScreenToWorld()} is used.
 	 */
-	public BufferedImage getMapImage() {
-		return mapImage;
+	public Envelope tranformGeoToWindow(final double ox, final double oy,
+			final double px, final double py,
+			final AffineTransform winToGeotransform) {
+		final AffineTransform at = winToGeotransform == null ? getScreenToWorld()
+				: winToGeotransform;
+		Point2D geoO;
+		try {
+			geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);
+			final Point2D geoP = at.inverseTransform(
+					new Point2D.Double(px, py), null);
+			return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP
+					.getY());
+		} catch (final NoninvertibleTransformException e) {
+			LOGGER.error(e);
+			return new Envelope(ox, oy, px, py);
+		}
 	}
 
 	/**
-	 * Set the BufferedImage to use as a flaoting icon in the lower right corner
+	 * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
 	 * 
-	 * @param mapImageIcon
-	 *            <code>null</code> is allowed and deactivates this icon.
+	 * @param ox
+	 *            X-Koordinate der VON-Position
+	 * @param oy
+	 *            Y-Koordinate der VON-Position
+	 * @param px
+	 *            X-Koordinate der BIS-Position
+	 * @param py
+	 *            Y-Koordinate der BIS-Position
 	 */
-	public void setMapImage(BufferedImage mapImage) {
-		this.mapImage = mapImage;
+	public Envelope tranformWindowToGeo(final int ox, final int oy,
+			final int px, final int py) {
+		final AffineTransform at = getScreenToWorld();
+		final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
+		final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
+		return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
 	}
 
 	/**
-	 * Lazyly initializes a {@link BufferedImage} for the background renderer.
+	 * Will update the cursor. If all rendering is finished also stops the
+	 * {@link #repaintTimer}
 	 */
-	private BufferedImage getLocalImage() {
+	public void updateCursor() {
 
-		if (localImage == null) {
-			localImage = new BufferedImage(getBounds().width,
-					getBounds().height, BufferedImage.TYPE_INT_ARGB);
+		// if the renderers have stopped, also stop the timer that is updating
+		// the final image
+		if (bgExecuter != null && bgExecuter.isRunning()
+				|| localExecuter != null && localExecuter.isRunning()) {
+			setCursor(WAIT_CURSOR);
+			return;
+		} else {
+			// Allow one last rendering
+			if (repaintTimer.isRunning()) {
+				repaintTimer.stop();
+				updateFinalImage();
+				repaint();
+			}
 		}
 
-		return localImage;
-	}
+		// wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
+		// von der aktuellen Aktion
+		if (this.staticCursor != null) {
+			setCursor(staticCursor);
+			return;
+		}
+		if (getCursor() == SwingUtil.PANNING_CURSOR) {
+			// This cursor will reset itself
+			return;
+		}
 
-	/**
-	 * Called by the {@linkplain XMapPane.RenderingTask} when rendering has been
-	 * completed Publishes a {@linkplain MapPaneEvent} of type {@code
-	 * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
-	 * 
-	 * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
-	 */
-	public void onRenderingCompleted() {
-		repainterTimer.stop();
-		updateFinalImage();
-		repaint();
+		// Set the cursor depending on what tool is in use...
+		switch (state) {
+		case SELECT_TOP:
+		case SELECT_ONE_FROM_TOP:
+		case SELECT_ALL:
+			setCursor(SwingUtil.CROSSHAIR_CURSOR);
+			break;
+		case ZOOM_IN:
+			setCursor(SwingUtil.ZOOMIN_CURSOR);
+			break;
+		case ZOOM_OUT:
+			setCursor(SwingUtil.ZOOMOUT_CURSOR);
+			break;
+		case PAN:
+			setCursor(SwingUtil.PAN_CURSOR);
+			break;
+		default:
+			setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+			break;
+		}
 	}
 
 	/**
-	 * Called by the {@linkplain XMapPane.RenderingTask} when rendering was
-	 * cancelled. Publishes a {@linkplain MapPaneEvent} of type {@code
-	 * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
-	 * 
-	 * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
+	 * The renderers are all rendering into their own {@link Image}s. This
+	 * method combines all images to one {@link #finalImage}. The
+	 * {@link #repaintTimer} is calling this method regularely to update the
+	 * {@link #finalImage} even if the renderers are still working.
 	 */
-	public void onRenderingCancelled() {
-		repainterTimer.stop();
-		LOGGER.debug("Rendering cancelled");
-	}
+	synchronized protected Image updateFinalImage() {
 
-	/**
-	 * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
-	 * Publishes a {@linkplain MapPaneEvent} of type {@code
-	 * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
-	 * 
-	 * @param renderingError
-	 *            The error that occured during rendering
-	 * 
-	 * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
-	 */
-	public void onRenderingFailed(Exception renderingError) {
-		repainterTimer.stop();
-		LOGGER.warn("Rendering failed", renderingError);
-		updateFinalImage();
-		repaint();
+		// Render the two map images first, into the preFinalImage
+		if (bgExecuter != null) {
+			final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
+					.getGraphics();
+			preFinalG.setBackground(getMapBackgroundColor());
 
-	}
+			preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
+					null);
 
-	/**
-	 * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
-	 * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
-	 * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br/>
-	 * Since 21. April 09: Before thecalculation starts, the aspect ratio is
-	 * corrected. This change implies, that setMapArea() will most of the time
-	 * not allow setting to a wrong aspectRatio.
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
-	 */
-	public Envelope bestAllowedMapArea(Envelope env) {
-		if (getWidth() == 0)
-			return env;
-		if (env == null)
-			return null;
+			// // Draw the local layers image
+			preFinalG.drawImage(getLocalImage(), 0, 0, null);
+			preFinalG.dispose();
 
-		Envelope newArea = null;
-
-		/**
-		 * Correct the aspect Ratio before we check the rest. Otherwise we might
-		 * easily fail. We allow to grow here, because we don't check against
-		 * the maxExtend
-		 */
-		Rectangle curPaintArea = getVisibleRect();
-
-		env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
-
-		final double scale = env.getWidth() / getWidth();
-		final double centerX = env.getMinX() + env.getWidth() / 2.;
-		final double centerY = env.getMinY() + env.getHeight() / 2.;
-		double newWidth2 = 0;
-		double newHeight2 = 0;
-		if (scale < getMaxZoomScale()) {
-			// ****************************************************************************
-			// Wir zoomen weiter rein als erlaubt => Anpassen des envelope
-			// ****************************************************************************
-			newWidth2 = getMaxZoomScale() * getWidth() / 2.;
-			newHeight2 = getMaxZoomScale() * getHeight() / 2.;
-		} else if (scale > getMinZoomScale()) {
-			// ****************************************************************************
-			// Wir zoomen weiter raus als erlaubt => Anpassen des envelope
-			// ****************************************************************************
-			newWidth2 = getMinZoomScale() * getWidth() / 2.;
-			newHeight2 = getMinZoomScale() * getHeight() / 2.;
 		} else {
-			// ****************************************************************************
-			// Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen
-			// ****************************************************************************
-			newArea = env;
+			preFinalImage = getLocalImage();
 		}
 
-		if (newArea == null) {
+		final Graphics2D finalG = getFinalImage().createGraphics();
+		finalG.setBackground(getMapBackgroundColor());
+		finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
+				getMapBackgroundColor(), null);
 
-			final Coordinate ll = new Coordinate(centerX - newWidth2, centerY
-					- newHeight2);
-			final Coordinate ur = new Coordinate(centerX + newWidth2, centerY
-					+ newHeight2);
+		final int finalImageHeight = getFinalImage().getHeight(null);
+		final int finalImageWidth = getFinalImage().getWidth(null);
 
-			newArea = new Envelope(ll, ur);
-		}
+		final Rectangle painedArea = new Rectangle(imageOrigin.x,
+				imageOrigin.y, finalImageWidth, finalImageHeight);
+		SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
 
-		Envelope maxAllowedExtend = getMaxExtend();
-		while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
-				&& newArea != null && !newArea.isNull()
-				&& !Double.isNaN(newArea.getMinX())
-				&& !Double.isNaN(newArea.getMaxX())
-				&& !Double.isNaN(newArea.getMinY())
-				&& !Double.isNaN(newArea.getMaxY())) {
-			/*
-			 * If a maxExtend is set, we have to honour that...
-			 */
+		addGadgets(finalG);
 
-			// Exceeds top? Move down and maybe cut
-			if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
-				double divY = newArea.getMaxY() - maxAllowedExtend.getMaxY();
-				// LOGGER.debug("Moving area down by " + divY);
+		finalG.dispose();
 
-				newArea = new Envelope(new Coordinate(newArea.getMinX(),
-						newArea.getMinY() - divY), new Coordinate(newArea
-						.getMaxX(), newArea.getMaxY() - divY));
-
-				if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
-					// LOGGER.debug("Now it exeeds the bottom border.. cut!");
-					// And cut the bottom if it moved out of the area
-					newArea = new Envelope(new Coordinate(newArea.getMinX(),
-							maxAllowedExtend.getMinY()), new Coordinate(newArea
-							.getMaxX(), newArea.getMaxY()));
-
-					// LOGGER.debug("and fix aspect ratio");
-
-					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
-							false);
-				}
-			}
-
-			// Exceeds bottom? Move up and maybe cut
-			if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
-				double divY = newArea.getMinY() - maxAllowedExtend.getMinY();
-				// LOGGER.debug("Moving area up by " + divY);
-
-				newArea = new Envelope(new Coordinate(newArea.getMinX(),
-						newArea.getMinY() - divY), new Coordinate(newArea
-						.getMaxX(), newArea.getMaxY() - divY));
-
-				if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
-					// LOGGER.debug("Now it exeeds the top border.. cut!");
-					// And cut the bottom if it moved out of the area
-					newArea = new Envelope(new Coordinate(newArea.getMinX(),
-							newArea.getMinY()), new Coordinate(newArea
-							.getMaxX(), maxAllowedExtend.getMaxY()));
-
-					// LOGGER.debug("and fix aspect ratio");
-
-					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
-							false);
-				}
-			}
-
-			// Exceeds to the right? move and maybe cut
-			if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
-
-				// Move left..
-				double divX = newArea.getMaxX() - maxAllowedExtend.getMaxX();
-				// LOGGER.debug("Moving area left by " + divX);
-
-				newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
-						newArea.getMinY()), new Coordinate(newArea.getMaxX()
-						- divX, newArea.getMaxY()));
-
-				if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
-					// LOGGER.debug("Now it exeeds the left border.. cut!");
-					// And cut the left if it moved out of the area
-					newArea = new Envelope(new Coordinate(maxAllowedExtend
-							.getMinX(), newArea.getMinY()), new Coordinate(
-							newArea.getMaxX(), newArea.getMaxY()));
-
-					// LOGGER.debug("and fix aspect ratio");
-
-					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
-							false);
-				}
-			}
-
-			// Exceeds to the left? move and maybe cut
-			if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
-
-				// Move right..
-				double divX = newArea.getMinX() - maxAllowedExtend.getMinX();
-				// LOGGER.debug("Moving area right by " + divX);
-
-				newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
-						newArea.getMinY()), new Coordinate(newArea.getMaxX()
-						- divX, newArea.getMaxY()));
-
-				if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
-					// LOGGER.debug("Now it exeeds the right border.. cut!");
-					// And cut the left if it moved out of the area
-					newArea = new Envelope(new Coordinate(newArea.getMinX(),
-							newArea.getMinY()), new Coordinate(maxAllowedExtend
-							.getMaxX(), newArea.getMaxY()));
-
-					// LOGGER.debug("and fix aspect ratio");
-
-					newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
-							false);
-				}
-			}
-		}
-
-		return newArea;
+		return finalImage;
 	}
 
 	/**
-	 * Retuns the minimum allowed zoom scale. This is the bigger number value of
-	 * the two. Defaults to {@link Double}.MAX_VALUE
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
+	 * Paints some optional stuff into the given {@link Graphics2D}. Usually
+	 * called as the last layer when {@link #updateFinalImage()}
 	 */
-	public Double getMinZoomScale() {
-		return minZoomScale;
-	}
+	private void addGadgets(final Graphics2D graphics) {
 
-	/**
-	 * Retuns the maximum allowed zoom scale. This is the smaller number value
-	 * of the two. Defaults to {@link Double}.MIN_VALUE
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
-	 */
-	public Double getMaxZoomScale() {
-		return maxZoomScale;
-	}
+		// Paint a logo to the bottom right if available
+		if (mapImage != null) {
+			graphics.drawImage(mapImage, getBounds().width
+					- mapImage.getWidth() - 10, getBounds().height
+					- mapImage.getHeight() - 10, null);
+		}
 
-	/**
-	 * Set the maximum allowed zoom scale. This is the smaller number value of
-	 * the two. If <code>null</code> is passed, Double.MINVALUE are used which
-	 * mean there is no restriction.
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
-	 */
-	public void setMaxZoomScale(final Double maxZoomScale) {
-		this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
-				: maxZoomScale;
-	}
+		// If the rendering process is still running, indicate this is the image
+		if (bgExecuter != null && bgExecuter.isRunning()
+				|| localExecuter != null && localExecuter.isRunning()) {
 
-	/**
-	 * Set the minimum (nearest) allowed zoom scale. This is the bigger number
-	 * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
-	 * used which mean there is no restriction.
-	 * 
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
-	 */
-	public void setMinZoomScale(final Double minZoomScale) {
-		this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
-				: minZoomScale;
-	}
+			final Color c = graphics.getColor();
+			graphics.setFont(waitFont);
+			String waitStr = "Wait..."; //i8n
+			
+			graphics.setColor(Color.WHITE);
+			graphics.drawString(waitStr, 39, 69); 
+			graphics.setColor(Color.BLACK);
+			graphics.drawString(waitStr, 40, 70); 
 
-	/**
-	 * Defines an evelope of the viwable area. The JMapPane will never show
-	 * anything outside of this extend.
-	 * 
-	 * @param maxExtend
-	 *            <code>null</code> to not have this restriction.
-	 */
-	public void setMaxExtend(Envelope maxExtend) {
-		this.maxExtend = maxExtend;
-	}
-
-	/**
-	 * Returns the evelope of the viewable area. The JMapPane will never show
-	 * anything outside of this extend. If this has been set to
-	 * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return
-	 * quickly the context's bounds. It it takes to long to determine the
-	 * context bounds, <code>null</code> is returned.
-	 * 
-	 * @param maxExtend
-	 *            <code>null</code> to not have this restriction.
-	 */
-
-	public Envelope getMaxExtend() {
-		if (maxExtend == null) {
-			final ReferencedEnvelope layerBounds = GTUtil
-					.getVisibleLayoutBounds(localContext);
-			if (layerBounds == null) {
-				// TODO Last fallback could be the CRS valid area
-				return null;
-			}
-
-			// Kartenbereich um 10% vergroessern
-			return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil
-					.expandEnvelope(layerBounds, 0.1), true);
+			graphics.setColor(c);
 		}
-		return maxExtend;
-	}
 
-	/**
-	 * Set the background color of the map.
-	 * 
-	 * @param if <code>null</code>, white is used.
-	 */
-	public void setMapBackgroundColor(Color bgColor) {
-		if (bgColor == null)
-			bgColor = Color.WHITE;
-		this.mapBackgroundColor = bgColor;
 	}
 
 	/**
-	 * Returns the background {@link Color} of the map pane. Default is white.
-	 **/
-	public Color getMapBackgroundColor() {
-		return mapBackgroundColor;
-	}
-
-	/**
+	 * Sets the {@link #mapArea} to best possibly present the given features. If only one
+	 * single point is given, the window is moved over the point.
 	 * 
-	 * @param b
+	 * @param features
+	 *            if <code>null</code> or size==0, the function doesn nothing.
 	 */
-	public void setPainting(boolean b) {
-		acceptsRepaintCalls = b;
-	}
+	public void zoomTo(
+			final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
 
-	/**
-	 * Fuegt der Map einen Listener hinzu.
-	 * 
-	 * @param l
-	 *            neuer Listener
-	 */
-	public void addMapPaneListener(JMapPaneListener l) {
-		mapPaneListeners.add(l);
-	}
+		final CoordinateReferenceSystem mapCRS = getContext()
+				.getCoordinateReferenceSystem();
+		final CoordinateReferenceSystem fCRS = features.getSchema()
+				.getGeometryDescriptor().getCoordinateReferenceSystem();
 
-	/**
-	 * Liste der angeschlossenen Listener, die auf Aktionen des MapPanes
-	 * lauschen.
-	 */
-	protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
+		double width = mapArea.getWidth();
+		double height = mapArea.getHeight();
+		final double ratio = height / width;
 
-	/**
-	 * A flag indicating if dispose() was already called. If true, then further
-	 * use of this {@link SelectableXMapPane} is undefined.
-	 */
-	private boolean disposed = false;
-
-	/**
-	 * Entfernt einen Listener von der Map.
-	 * 
-	 * @param l
-	 *            zu entfernender Listener
-	 */
-	public void removeMapPaneListener(JMapPaneListener l) {
-		mapPaneListeners.remove(l);
-	}
-
-//	/** Stored the time used for the last real rendering in ms. **/
-//	private long lastRenderingDuration = Long.MAX_VALUE;
-
-	// if null, no quick preview will be shown
-	private int quickPreviewHint = 0;
-
-	/**
-	 * For every rendering thread started,
-	 * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
-	 * renderer. These Java2D rendering hints are passed to the
-	 * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
-	 * and local).
-	 */
-	private RenderingHints java2dHints;
-
-//	/**
-//	 * Returns in milli seconds the time the last rending of the
-//	 * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has not
-//	 * been rendered yet.
-//	 */
-//	public long getLastRenderingDuration() {
-//		return lastRenderingDuration;
-//	}
-
-	/**
-	 * Should be called when the {@link JMapPane} is not needed no more to help
-	 * the GarbageCollector
-	 * 
-	 * Removes all {@link JMapPaneListener}s that are registered
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
-	 */
-	public void dispose() {
-		if (isDisposed())
+		if (features == null || features.size() == 0) {
+			// feature count == 0 Zoom to the full extend
 			return;
+		} else if (features.size() == 1) {
 
-		setPainting(false);
-		
-		resizeTimer.stop();
-		startRenderThreadsTimer.stop();
+			// feature count == 1 Just move the window to the point and zoom 'a
+			// bit'
+			final SimpleFeature singleFeature = features.iterator().next();
 
-		disposed = true;
+			if (((Geometry) singleFeature.getDefaultGeometry())
+					.getCoordinates().length > 1) {
+				// System.out.println("Zoomed to only pne poylgon");
+				// Poly
+				// TODO max width vs. height
+				width = features.getBounds().getWidth() * 3;
+				height = ratio * width;
+			} else {
+				// System.out.println("Zoomed in a bit becasue only one point");
+				// width *= .9;
+				// height *= .9;
+			}
 
-		if (bgExecuter != null) {
-			bgExecuter.cancelTask();
-			bgExecuter.dispose();
-		}
-
-		if (localExecuter != null) {
-			int i = 0;
-			localExecuter.cancelTask();
-			while (i++ < 10 && localExecuter.isRunning()){
+			Coordinate centre = features.getBounds().centre();
+			if (!mapCRS.equals(fCRS)) {
+				// only to calculations if the CRS differ
 				try {
-					Thread.sleep(200);
-				} catch (InterruptedException e) {
-					// TODO Auto-generated catch block
-					e.printStackTrace();
+					MathTransform fToMap;
+					fToMap = CRS.findMathTransform(fCRS, mapCRS);
+					// centre is transformed to the mapCRS
+					centre = JTS.transform(centre, null, fToMap);
+				} catch (final FactoryException e) {
+					LOGGER.error("Looking for a Math transform", e);
+				} catch (final TransformException e) {
+					LOGGER.error("Looking for a Math transform", e);
 				}
 			}
-			if (localExecuter.isRunning()) {
-				System.out.println("BAD BAD BAD... still running the thread....");
-			}
-			localExecuter.dispose();
-		}
 
+			final Coordinate newLeftBottom = new Coordinate(centre.x - width
+					/ 2., centre.y - height / 2.);
+			final Coordinate newTopRight = new Coordinate(
+					centre.x + width / 2., centre.y + height / 2.);
 
-		if (bgImage != null) {
-			bgImage = dispose(bgImage);
-			bgImage = null;
-//			LangUtil.gcTotal();
-		}
+			final Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
 
-		if (localImage != null) {
-			localImage = dispose(localImage);
-			localImage = null;
-//			LangUtil.gcTotal();
-		}
+			setMapArea(newMapArea);
 
-		if (finalImage != null) {
-			finalImage = dispose(finalImage);
-			finalImage = null;
-//			LangUtil.gcTotal();
-		}
+		} else {
+			final ReferencedEnvelope fBounds = features.getBounds();
 
-		if (preFinalImage != null) {
-			preFinalImage = dispose(preFinalImage);
-			preFinalImage=null;
-		}
-		
-//		LangUtil.gcTotal();
+			Envelope bounds;
+			if (!mapCRS.equals(fCRS)) {
+				bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);
+			} else {
+				bounds = fBounds;
+			}
+			// BB umrechnen von Layer-CRS in Map-CRS
 
-		// Alle mapPaneListener entfernen
-		mapPaneListeners.clear();
+			// Expand a bit
+			bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
 
-		removeMouseMotionListener(zoomMapPaneMouseListener);
-		removeMouseListener(zoomMapPaneMouseListener);
-
-		if (localContext != null)
-			getContext().clearLayerList();
-		if (bgContext != null)
-			getBgContext().clearLayerList();
-
-		removeAll();
+			setMapArea(bounds);
+		}
 	}
 
-	private BufferedImage dispose(BufferedImage bi) {
-
-//		System.out.println("vorher = "
-//			+ new MbDecimalFormatter().format(LangUtil.gcTotal()));
-		bi.flush();
-		return bi = null;
-//		System.out.println("nacher = "
-//				+ new MbDecimalFormatter().format(LangUtil.gcTotal()));
-//
-//		System.out.println("\n");
-	}
-
 	/**
-	 * A flag indicating if dispose() has already been called. If true, then
-	 * further use of this {@link SelectableXMapPane} is undefined.
+	 * Zooms towards a point.
+	 * 
+	 * @param center
+	 *            position in window coordinates
+	 * @param zoomFactor
+	 *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
 	 */
-	private boolean isDisposed() {
-		return disposed;
+	public void zoomTo(final Point center) {
+		zoomTo(center, null);
 	}
 
-	public void setQuickPreviewHint(int quickPreviewHint) {
-		this.quickPreviewHint = quickPreviewHint;
-
-	}
-
-	public void setJava2dHints(RenderingHints java2dHints) {
-		this.java2dHints = java2dHints;
-	}
-
-	public RenderingHints getJava2dHints() {
-		return java2dHints;
-	}
-
 	/**
 	 * Zooms towards a point.
 	 * 
@@ -2062,7 +2237,7 @@
 		if (zoomFaktor == null || zoomFaktor == 0.)
 			zoomFaktor = 2.;
 
-		Point2D gcenter = getScreenToWorld().transform(center, null);
+		final Point2D gcenter = getScreenToWorld().transform(center, null);
 		center = null;
 
 		if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
@@ -2076,7 +2251,7 @@
 
 		final Envelope mapArea = getMapArea();
 
-		Envelope newMapArea = new Envelope(mapArea);
+		final Envelope newMapArea = new Envelope(mapArea);
 		newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
 				.getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
 				.getHeight()) / 2.);
@@ -2089,144 +2264,4 @@
 		setMapArea(newMapArea);
 	}
 
-	/**
-	 * Zooms towards a point.
-	 * 
-	 * @param center
-	 *            position in window coordinates
-	 * @param zoomFactor
-	 *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
-	 */
-	public void zoomTo(Point center) {
-		zoomTo(center, null);
-	}
-
-	public void mouseDragged(Point startPos, Point lastPos, MouseEvent event) {
-
-		if ((getState() == XMapPane.PAN)
-				|| ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
-
-			if (getCursor() != SwingUtil.PANNING_CURSOR) {
-				setCursor(SwingUtil.PANNING_CURSOR);
-
-				// While panning, we deactivate the rendering. So the tasts are
-				// ready to start when the panning os done.
-				if (bgExecuter != null)
-					bgExecuter.cancelTask();
-				if (localExecuter != null)
-					localExecuter.cancelTask();
-			}
-
-			if (lastPos.x > 0 && lastPos.y > 0) {
-				final int dx = event.getX() - lastPos.x;
-				final int dy = event.getY() - lastPos.y;
-
-				// TODO Stop dragging when the drag would not be valid...
-				// boolean dragValid = true;
-				// // check if this panning results in a valid mapArea
-				// {
-				// Rectangle winBounds = xMapPane.getBounds();
-				// winBounds.translate(xMapPane.imageOrigin.x,
-				// -xMapPane.imageOrigin.y);
-				// Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
-				// winBounds.x, winBounds.y, winBounds.x
-				// + winBounds.width, winBounds.y
-				// + winBounds.height);
-				//					
-				//
-				// winBounds = xMapPane.getBounds();
-				// Point testIng = new Point(xMapPane.imageOrigin);
-				// testIng.translate(dx, dy);
-				// winBounds.translate(testIng.x, -testIng.y);
-				// Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
-				// winBounds.x, winBounds.y, winBounds.x
-				// + winBounds.width, winBounds.y
-				// + winBounds.height);
-				//
-				// // If the last drag doesn't change the MapArea anymore cancel
-				// it.
-				// if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
-				// xMapPane.bestAllowedMapArea(newMapAreaBefore))){
-				// dragValid = false;
-				// return;
-				// }
-				// }
-
-				imageOrigin.translate(dx, dy);
-				updateFinalImage();
-				repaint();
-			}
-
-		} else if ((getState() == XMapPane.ZOOM_IN)
-				|| (getState() == XMapPane.ZOOM_OUT)
-				|| (getState() == XMapPane.SELECT_ALL)
-				|| (getState() == XMapPane.SELECT_TOP)
-		// || (getState() == XMapPane.SELECT_ONE_FROM_TOP)
-		) {
-			final Graphics graphics = getGraphics();
-
-			drawRectangle(graphics, startPos, event.getPoint());
-
-			if ((lastPos.x > 0) && (lastPos.y > 0)) {
-				drawRectangle(graphics, startPos, lastPos);
-			}
-
-			graphics.dispose();
-
-		}
-
-	}
-
-	/**
-	 * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
-	 * given point. All in screen coordinates.
-	 */
-	protected void drawRectangle(final Graphics graphics, Point startPos,
-			Point e) {
-
-		if (!isWellDefined())
-			return;
-
-		// undraw last box/draw new box
-		final int left = Math.min(startPos.x, e.x);
-		final int right = Math.max(startPos.x, e.x);
-		final int top = Math.max(startPos.y, e.y);
-		final int bottom = Math.min(startPos.y, e.y);
-		final int width = right - left;
-		final int height = top - bottom;
-
-		if (width == 0 && height == 0)
-			return;
-
-		graphics.setXORMode(Color.WHITE);
-		graphics.drawRect(left, bottom, width, height);
-	}
-
-	/**
-	 * Finalizes a PAN action
-	 */
-	public void performPan() {
-		Rectangle winBounds = getBounds();
-		winBounds.translate(-imageOrigin.x, -imageOrigin.y);
-		Envelope newMapArea = tranformWindowToGeo(winBounds.x, winBounds.y,
-				winBounds.x + winBounds.width, winBounds.y + winBounds.height);
-
-		imageOrigin.x = 0;
-		imageOrigin.y = 0;
-
-		if (!setMapArea(newMapArea)) {
-			updateFinalImage();
-			repaint();
-		}
-
-		if (getCursor() == SwingUtil.PANNING_CURSOR)
-			setCursor(SwingUtil.PAN_CURSOR);
-	}
-
-	public void onRenderingPending() {
-		// LOGGER.debug("Pending rendering updates the preview...");
-		updateFinalImage();
-		repaint();
-	}
-
 }

Modified: branches/1.0-gt2-2.6/src/schmitzm/swing/SwingUtil.java
===================================================================
--- branches/1.0-gt2-2.6/src/schmitzm/swing/SwingUtil.java	2009-11-18 20:47:00 UTC (rev 529)
+++ branches/1.0-gt2-2.6/src/schmitzm/swing/SwingUtil.java	2009-11-19 09:31:14 UTC (rev 530)
@@ -876,8 +876,6 @@
 	 *             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();
@@ -966,12 +964,15 @@
 	/**
 	 * 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.
+	 * "Expanding or Collapsing all Nodes in a JTree Component".<br/>
+	 * 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
+	 * @param expand
+	 *            If <code>true</code> all nodfes will be expanded, otherwise
+	 *            they will be collapsed.
 	 */
 	public static void expandAll(JTree tree, boolean expand) {
 		TreeNode root = (TreeNode) tree.getModel().getRoot();
@@ -980,22 +981,29 @@
 		expandAll(tree, new TreePath(root), expand);
 	}
 
-	private static void expandAll(JTree tree, TreePath parent, boolean expand) {
+	/**
+	 * If expand is <code>true</code>, expands all nodes on the way down the
+	 * path.
+	 * 
+	 * @param tree
+	 *            {@link JTree} to expand or collapse
+	 */
+	public static void expandAll(JTree tree, TreePath path, boolean expand) {
 		// Traverse children
-		TreeNode node = (TreeNode) parent.getLastPathComponent();
+		TreeNode node = (TreeNode) path.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);
+				TreePath path2 = path.pathByAddingChild(n);
+				expandAll(tree, path2, expand);
 			}
 		}
 
 		// Expansion or collapse must be done bottom-up
 		if (expand) {
-			tree.expandPath(parent);
+			tree.expandPath(path);
 		} else {
-			tree.collapsePath(parent);
+			tree.collapsePath(path);
 		}
 	}
 
@@ -1003,9 +1011,6 @@
 	 * 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&uuml;ger</a>
 	 */
 	public static void maximize(Frame frame) {
 		int state = frame.getExtendedState();
@@ -1019,9 +1024,6 @@
 
 	/**
 	 * This method deiconifies a frame; the maximized bits are not affected.
-	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Kr&uuml;ger</a>
 	 */
 	public static void deiconify(JFrame frame) {
 		int state = frame.getExtendedState();
@@ -1036,11 +1038,12 @@
 
 	/**
 	 * Allows to define a renderer and min- and max width of a column with just
-	 * one line of code ;-)
+	 * one line of code. Just for convenience.
 	 * 
 	 * @param table
+	 *            A {@link JTable} to access the column model.
 	 * @param modelIdx
-	 *            column index in model
+	 *            column index in model counting
 	 * @param cellRenderer
 	 *            <code>null</code> allowed
 	 * @param minwidth
@@ -1068,16 +1071,19 @@
 	}
 
 	/**
-	 * Erase an image. This is much faster than recreating a new BufferedImage
+	 * Erase an image. This is much faster than recreating a new
+	 * {@link BufferedImage}.
 	 */
-	public static void clearImage(BufferedImage image) {
-		Graphics2D baseImageGraphics = (Graphics2D) image.getGraphics();
-		Composite composite = baseImageGraphics.getComposite();
-		baseImageGraphics.setComposite(AlphaComposite.Clear);
+	public static void clearImage(BufferedImage image, Color bgColor) {
+		Graphics2D graphics = image.createGraphics();
+		if (bgColor != null)
+			graphics.setBackground(bgColor);
+		Composite composite = graphics.getComposite();
+		graphics.setComposite(AlphaComposite.Clear);
 		Rectangle2D.Double rect = new Rectangle2D.Double(0, 0,
 				image.getWidth(), image.getHeight());
-		baseImageGraphics.fill(rect);
-		baseImageGraphics.setComposite(composite);
+		graphics.fill(rect);
+		graphics.setComposite(composite);
 	}
 
 	/**
@@ -1095,40 +1101,32 @@
 
 		// Clear left of the painted area if needed
 		if (clearArea.getMinX() < paintArea.getMinX()) {
-			graphics.clearRect(
-					(int) clearArea.getMinX(), 
-					(int) clearArea.getMinY(), 
-					(int) paintArea.getMinX(), 
-					(int) clearArea.getMaxY());
+			graphics.clearRect((int) clearArea.getMinX(), (int) clearArea
+					.getMinY(), (int) paintArea.getMinX(), (int) clearArea
+					.getMaxY());
 		}
 
 		// Clear right of the painted area if needed
 		if (clearArea.getMaxX() > paintArea.getMaxX()) {
-			graphics.clearRect(
-					(int) paintArea.getMaxX(), 
-					(int) clearArea.getMinY(), 
-					(int) clearArea.getMaxX(), 
-					(int) clearArea.getMaxY());
+			graphics.clearRect((int) paintArea.getMaxX(), (int) clearArea
+					.getMinY(), (int) clearArea.getMaxX(), (int) clearArea
+					.getMaxY());
 		}
-		
+
 		// Clear above of the painted area if needed
 		if (clearArea.getMinY() < paintArea.getMinY()) {
-			graphics.clearRect(
-					(int) clearArea.getMinX(), 
-					(int) clearArea.getMinY(), 
-					(int) clearArea.getMaxX(), 
-					(int) paintArea.getMinY());
+			graphics.clearRect((int) clearArea.getMinX(), (int) clearArea
+					.getMinY(), (int) clearArea.getMaxX(), (int) paintArea
+					.getMinY());
 		}
-		
+
 		// Clear below of the painted area if needed
 		if (clearArea.getMaxY() > paintArea.getMaxY()) {
-			graphics.clearRect(
-					(int) clearArea.getMinX(), 
-					(int) paintArea.getMaxY(), 
-					(int) clearArea.getMaxX(), 
-					(int) clearArea.getMaxY());
+			graphics.clearRect((int) clearArea.getMinX(), (int) paintArea
+					.getMaxY(), (int) clearArea.getMaxX(), (int) clearArea
+					.getMaxY());
 		}
-		
+
 	}
 
 }

Modified: branches/1.0-gt2-2.6/src/skrueger/geotools/RenderingExecutor.java
===================================================================
--- branches/1.0-gt2-2.6/src/skrueger/geotools/RenderingExecutor.java	2009-11-18 20:47:00 UTC (rev 529)
+++ branches/1.0-gt2-2.6/src/skrueger/geotools/RenderingExecutor.java	2009-11-19 09:31:14 UTC (rev 530)
@@ -2,151 +2,138 @@
 
 import gtmig.org.geotools.swing.XMapPane;
 
-import java.awt.AlphaComposite;
-import java.awt.Color;
-import java.awt.Composite;
 import java.awt.Graphics2D;
 import java.awt.Rectangle;
 import java.awt.geom.AffineTransform;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.geotools.geometry.jts.ReferencedEnvelope;
 import org.geotools.renderer.GTRenderer;
 import org.geotools.renderer.RenderListener;
-import org.geotools.swing.JMapPane;
 import org.opengis.feature.simple.SimpleFeature;
 
 public class RenderingExecutor {
 
-private volatile RenderThread task;
-private final XMapPane mapPane;
+	private volatile RenderThread renderThread;
+	private final XMapPane mapPane;
+
 	public RenderingExecutor(XMapPane mapPane) {
 		this.mapPane = mapPane;
-    }
+	}
 
+	/**
+	 * Submit a new rendering task. If no rendering task is presently running
+	 * this new task will be accepted; otherwise it will be rejected (ie. there
+	 * is no task queue).
+	 * 
+	 * @param envelope
+	 *            the map area (world coordinates) to be rendered
+	 * @param graphics
+	 *            the graphics object to draw on
+	 * 
+	 * @return true if the rendering task was accepted; false if it was rejected
+	 */
+	public synchronized boolean submit(ReferencedEnvelope envelope,
+			Rectangle paintArea, Graphics2D graphics,
+			final GTRenderer renderer, AffineTransform worldToScreen) {
+		System.out.println("submit..:");
+		if (renderThread == null || !renderThread.isAlive()) {
+			System.out.println("is vacant... starting thread!");
 
-    /**
-     * Submit a new rendering task. If no rendering task is presently running
-     * this new task will be accepted; otherwise it will be rejected (ie. there
-     * is no task queue).
-     *
-     * @param envelope the map area (world coordinates) to be rendered
-     * @param graphics the graphics object to draw on
-     *
-     * @return true if the rendering task was accepted; false if it was
-     *         rejected
-     */
-    public synchronized boolean submit(ReferencedEnvelope envelope, Rectangle paintArea, Graphics2D graphics, final GTRenderer renderer, AffineTransform worldToScreen) {
-    	System.out.println("submit..:");
-    	if (task == null || !task.isAlive()) {
-    		System.out.println("is vacant... starting thread!");
-    		
-        	task = new RenderThread(paintArea, graphics, renderer, worldToScreen);
-        	task.start();
-        	
-            return true;
-        } else {
-        	System.out.println("is busy... requesting stop!");
-        	task.getRenderer().stopRendering();
-        }
+			renderThread = new RenderThread(paintArea, graphics, renderer,
+					worldToScreen);
+			renderThread.start();
 
-        return false;
-    }
-    
-    class RenderThread extends Thread  {
-    	
-    	private final GTRenderer renderer;
-//		private final Rectangle paintArea;
-//		private final AffineTransform worldToScreen;
-//		private final Graphics2D graphics;
+			return true;
+		} else {
+			System.out.println("is busy... requesting stop!");
+			renderThread.getRenderer().stopRendering();
+		}
 
-		public RenderThread(final Rectangle paintArea, final Graphics2D graphics, GTRenderer renderer, AffineTransform worldToScreen) {
-			super( new RenderRun(paintArea, graphics, renderer, worldToScreen));
-//			this.paintArea = paintArea;
-//			this.graphics = graphics;
+		return false;
+	}
+
+	class RenderThread extends Thread {
+
+		private final GTRenderer renderer;
+
+		public RenderThread(final Rectangle paintArea,
+				final Graphics2D graphics, GTRenderer renderer,
+				AffineTransform worldToScreen) {
+			super(new RenderRun(paintArea, graphics, renderer, worldToScreen));
 			this.renderer = renderer;
-//			this.worldToScreen = worldToScreen;
-			
-			System.out.println("starting render thread "+getName());
+
+			System.out.println("starting render thread " + getName());
 		}
-    	
-    	public GTRenderer getRenderer() {
+
+		public GTRenderer getRenderer() {
 			return renderer;
 		}
 
-    }
-    
-    class RenderRun implements Runnable, RenderListener  {
-    	private final Rectangle paintArea;
+	}
+
+	class RenderRun implements Runnable, RenderListener {
+		private final Rectangle paintArea;
 		private final Graphics2D graphics;
 		private final AffineTransform worldToScreen;
 		private final GTRenderer renderer;
 
 		public RenderRun(Rectangle paintArea, Graphics2D graphics,
 				GTRenderer renderer, AffineTransform worldToScreen) {
-					this.paintArea = paintArea;
-					this.graphics = graphics;
-					this.renderer = renderer;
-					this.worldToScreen = worldToScreen;
+			this.paintArea = paintArea;
+			this.graphics = graphics;
+			this.renderer = renderer;
+			this.worldToScreen = worldToScreen;
 		}
+
 		@Override
 		public void run() {
 			try {
-    			renderer.addRenderListener(this);
-    			System.out.println("start rendering...");
-    			try {
+				renderer.addRenderListener(this);
+				System.out.println("start rendering...");
+				try {
 					Thread.sleep(1000);
 				} catch (InterruptedException e) {
 					// TODO Auto-generated catch block
 					e.printStackTrace();
 				}
-    			renderer.paint(graphics, paintArea, worldToScreen);
-    			
-    			mapPane.onRenderingCompleted();
-    		} finally {
-    			renderer.removeRenderListener(this);
-    		}
+				renderer.paint(graphics, paintArea, worldToScreen);
+
+				mapPane.onRenderingCompleted();
+			} finally {
+				renderer.removeRenderListener(this);
+			}
 		}
+
 		@Override
 		public void errorOccurred(Exception e) {
-//			System.out.println("rendering error");
+			// System.out.println("rendering error");
 			mapPane.onRenderingFailed(e);
 		}
 
 		@Override
 		public void featureRenderer(SimpleFeature feature) {
 		}
-    	
-    }
 
+	}
+
 	public void cancelTask() {
-		if (task!=null && task.isAlive()) {
-//			System.out.println("request stop for thread " +task.getName());
-			task.getRenderer().stopRendering();
+		if (renderThread != null && renderThread.isAlive()) {
+			// System.out.println("request stop for thread " +task.getName());
+			renderThread.getRenderer().stopRendering();
 		}
 	}
 
 	public boolean isRunning() {
-//		if (task != null) 
-//			System.out.println("is running "+task.getName()+" = true");
-		return (task != null && task.isAlive());
+		// if (task != null)
+		// System.out.println("is running "+task.getName()+" = true");
+		return (renderThread != null && renderThread.isAlive());
 	}
 
 	public void dispose() {
-		if (task != null) {
-			task.renderer.stopRendering();
-			task = null;
+		if (renderThread != null) {
+			renderThread.renderer.stopRendering();
+			renderThread = null;
 		}
 	}
-    
 
 }
-



More information about the Schmitzm-commits mailing list