Newer
Older
abgabensammlungSS15 / ea / ub8 / framework / DDrawing / DGrid.java
@MaxXximus92 MaxXximus92 on 20 Jun 2015 2 KB ea code
package DDrawing;


import java.awt.Color ;
import java.awt.Graphics ;


/**
 * this class paints a grid with certain line distances on a DParent
 */
public class DGrid extends DComponent{

  /**
   * the distances between the lines
   */
  double hor_dist;
  /**
   * the distances between the lines
   */
  double ver_dist;

  private Color DEFAULT_COLOR = Color.lightGray;

  /**
   * constructor with the size and position of the grid and the line distances
   *
   * @param rectangle the rectangle around the grid
   * @param hor_dist the horizontal distance between the lines in D-coordinates,
   *        not in pixel coordinates!
   * @param ver_dist vertical distance between the lines in D-coordinates,
   *        not in pixel coordinates!
   */
  public DGrid( DRectangle rectangle, double hor_dist, double ver_dist ){
    this.rectangle = rectangle;
    this.hor_dist = hor_dist;
    this.ver_dist = ver_dist;
    color = DEFAULT_COLOR;
  }

  /**
   * constructor with the size and position of the grid and the line distances
   *
   * @param rectangle the rectangle around the grid
   * @param hor_dist the horizontal distance between the lines in D-coordinates,
   *        not in pixel coordinates!
   * @param ver_dist the vertical distance between the lines in D-coordinates,
   *        not in pixel coordinates!
   * @param color the color of the grid
   *        ( can also be set by setColor( java.awt.Color ) )
   */
  public DGrid( DRectangle rectangle, double hor_dist, double ver_dist, Color color ){
    this.rectangle = rectangle;
    this.hor_dist = hor_dist;
    this.ver_dist = ver_dist;
    this.color = color;
  }

  /**
   * paints the grid...
   *
   * @param m the <code>DMeasures</code> object to paint the grid
   */
  public void paint( DMeasures m ){
    Graphics g = m.getGraphics();
    Color old_color = g.getColor();
    if( color != null ) g.setColor( color );
    else g.setColor( DEFAULT_COLOR );
    double minX, minY, pos;
    DPoint p1, p2;
    DLine l;

    minX = (int)( rectangle.x / hor_dist );
    if( minX * hor_dist <= rectangle.x ) minX++;
    minX *= hor_dist;
    minY = (int)( rectangle.y / ver_dist );
    if( minY * ver_dist <= rectangle.y ) minY++;
    minY *= ver_dist;

    p1 = new DPoint( 0, rectangle.y );
    p2 = new DPoint( 0, rectangle.y + rectangle.height );
    for( pos = minX; pos<=rectangle.x + rectangle.width; pos += hor_dist ){
      p1.x = p2.x = pos;
      l = new DLine( p1, p2, color );
      l.paint( m );
    }

    p1.x = rectangle.x;
    p2.x = p1.x + rectangle.width;
    for( pos = minY; pos<=rectangle.y + rectangle.height; pos += ver_dist ){
      p1.y = p2.y = pos;
      l = new DLine( p1, p2, color );
      l.paint( m );
    }

    g.setColor( old_color );
  }

  public String toString(){
    return "DDrawing.DGrid[ hor: "+hor_dist+", ver: "+ver_dist+" ]";
  }
}