Draw Dotted Line
7
Draw a dotted line in Java.
private void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2, double dashlength, double spacelength)
{
if ((x1 == x2) && (y1 == y2))
{
g.drawLine(x1, y1, x2, y2);
return;
}
double linelength = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
double yincrement = (y2 - y1) / (linelength / (dashlength + spacelength));
double xincdashspace = (x2 - x1) / (linelength / (dashlength + spacelength));
double yincdashspace = (y2 - y1) / (linelength / (dashlength + spacelength));
double xincdash = (x2 - x1) / (linelength / (dashlength));
double yincdash = (y2 - y1) / (linelength / (dashlength));
int counter = 0;
for (double i = 0; i < linelength - dashlength; i += dashlength + spacelength)
{
g.drawLine((int) (x1 + xincdashspace * counter), (int) (y1 + yincdashspace * counter), (int) (x1 + xincdashspace * counter + xincdash), (int) (y1 + yincdashspace * counter + yincdash));
counter++;
}
if ((dashlength + spacelength) * counter <= linelength)
{
g.drawLine((int) (x1 + xincdashspace * counter), (int) (y1 + yincdashspace * counter), x2, y2);
}
}






Just as an aside, with Graphics2D, you can use the Stroke API
private void drawDashedLine( Graphics2D g, int x1, int y1, int x2, int y2, float dashlength, float spacelength, float width )
{
float[] dashValues = new float[] { dashLength, spaceLength } ;
Stroke stroke = new BasicStroke( width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dashvalues, 0 ) ;
g.setStroke( stroke ) ;
Line2D line = new Line2D.Double( x1, y1, x2, y2 ) ;
g.draw( line ) ;
}