Search code examples
javagraphicsgraphics2d

A dashed line without use of stroke in Java


Is is possible to draw a dashed line(non-continues) in java by using Graphics but without using stroke?

For example we have Shape line = new Line2D.Double() but this always creates a continues line.

I need this as i have to build things(Shapes) in a seperate class and draw them in other class and i have no way to force someone to draw a dashed line if he does not use stroke.


Solution

  • Yes you can, look at the single method in the interface Stroke: createStrokedShape:

    Stroke myStroke = ...;
    Shape line = new Line2D.Double();
    Shape stroked = myStroke.createStrokedShape(line);
    

    And then later you can fill the stroked shape:

    g2d.fill(stroked);