001// License: GPL. For details, see Readme.txt file.
002package org.openstreetmap.gui.jmapviewer;
003
004import java.awt.BasicStroke;
005import java.awt.Color;
006import java.awt.Graphics;
007import java.awt.Graphics2D;
008import java.awt.Point;
009import java.awt.Stroke;
010
011import org.openstreetmap.gui.jmapviewer.interfaces.MapRectangle;
012
013public class MapRectangleImpl extends MapObjectImpl implements MapRectangle {
014
015    private Coordinate topLeft;
016    private Coordinate bottomRight;
017
018    public MapRectangleImpl(Coordinate topLeft, Coordinate bottomRight) {
019        this(null, null, topLeft, bottomRight);
020    }
021    public MapRectangleImpl(String name, Coordinate topLeft, Coordinate bottomRight) {
022        this(null, name, topLeft, bottomRight);
023    }
024    public MapRectangleImpl(Layer layer, Coordinate topLeft, Coordinate bottomRight) {
025        this(layer, null, topLeft, bottomRight);
026    }
027    public MapRectangleImpl(Layer layer, String name, Coordinate topLeft, Coordinate bottomRight) {
028        this(layer, name, topLeft, bottomRight, getDefaultStyle());
029    }
030    public MapRectangleImpl(Layer layer, String name, Coordinate topLeft, Coordinate bottomRight, Style style) {
031        super(layer, name, style);
032        this.topLeft = topLeft;
033        this.bottomRight = bottomRight;
034    }
035
036    @Override
037    public Coordinate getTopLeft() {
038        return topLeft;
039    }
040
041    @Override
042    public Coordinate getBottomRight() {
043        return bottomRight;
044    }
045
046    @Override
047    public void paint(Graphics g, Point topLeft, Point bottomRight) {
048        // Prepare graphics
049        Color oldColor = g.getColor();
050        g.setColor(getColor());
051        Stroke oldStroke = null;
052        if (g instanceof Graphics2D) {
053            Graphics2D g2 = (Graphics2D) g;
054            oldStroke = g2.getStroke();
055            g2.setStroke(getStroke());
056        }
057        // Draw
058        g.drawRect(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
059        // Restore graphics
060        g.setColor(oldColor);
061        if (g instanceof Graphics2D) {
062            ((Graphics2D) g).setStroke(oldStroke);
063        }
064        int width=bottomRight.x-topLeft.x;
065        int height=bottomRight.y-topLeft.y;
066        Point p= new Point(topLeft.x+(width/2), topLeft.y+(height/2));
067        if(getLayer()==null||getLayer().isVisibleTexts()) paintText(g, p);
068    }
069
070    public static Style getDefaultStyle(){
071        return new Style(Color.BLUE, null, new BasicStroke(2), getDefaultFont());
072    }
073
074    @Override
075    public String toString() {
076        return "MapRectangle from " + getTopLeft() + " to " + getBottomRight();
077    }
078}