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
022    public MapRectangleImpl(String name, Coordinate topLeft, Coordinate bottomRight) {
023        this(null, name, topLeft, bottomRight);
024    }
025
026    public MapRectangleImpl(Layer layer, Coordinate topLeft, Coordinate bottomRight) {
027        this(layer, null, topLeft, bottomRight);
028    }
029
030    public MapRectangleImpl(Layer layer, String name, Coordinate topLeft, Coordinate bottomRight) {
031        this(layer, name, topLeft, bottomRight, getDefaultStyle());
032    }
033
034    public MapRectangleImpl(Layer layer, String name, Coordinate topLeft, Coordinate bottomRight, Style style) {
035        super(layer, name, style);
036        this.topLeft = topLeft;
037        this.bottomRight = bottomRight;
038    }
039
040    @Override
041    public Coordinate getTopLeft() {
042        return topLeft;
043    }
044
045    @Override
046    public Coordinate getBottomRight() {
047        return bottomRight;
048    }
049
050    @Override
051    public void paint(Graphics g, Point topLeft, Point bottomRight) {
052        // Prepare graphics
053        Color oldColor = g.getColor();
054        g.setColor(getColor());
055        Stroke oldStroke = null;
056        if (g instanceof Graphics2D) {
057            Graphics2D g2 = (Graphics2D) g;
058            oldStroke = g2.getStroke();
059            g2.setStroke(getStroke());
060        }
061        // Draw
062        g.drawRect(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
063        // Restore graphics
064        g.setColor(oldColor);
065        if (g instanceof Graphics2D) {
066            ((Graphics2D) g).setStroke(oldStroke);
067        }
068        int width = bottomRight.x-topLeft.x;
069        int height = bottomRight.y-topLeft.y;
070        Point p = new Point(topLeft.x+(width/2), topLeft.y+(height/2));
071        if (getLayer() == null || getLayer().isVisibleTexts()) paintText(g, p);
072    }
073
074    public static Style getDefaultStyle() {
075        return new Style(Color.BLUE, null, new BasicStroke(2), getDefaultFont());
076    }
077
078    @Override
079    public String toString() {
080        return "MapRectangle from " + getTopLeft() + " to " + getBottomRight();
081    }
082}