How can I draw a dotted line in AWT?

John Zukowski

Prior to introducing the Java 2D API into the Java 2 platform, all lines drawn were a single pixel wide solid lines of a single color. So, if you wanted a dotted line in 1.0 or 1.1, you had to do all the intermediate drawing steps yourself.

With the Java 2D API though, you can define a Stroke to define the drawing pen. For dotted lines, you would need to use the BasicStroke constructor that accepted six arguments:

public BasicStroke
  (float width,
   int cap,
   int join,
   float miterlimit,
   float[] dash,
   float dash_phase)

So, for a dotted line, an example might look like:

import java.awt.*;
import java.awt.geom.*;
import java.applet.*;

public class Stroked extends Applet {
  public void paint (Graphics g) {
    Graphics2D g2d = (Graphics2D)g;

    Rectangle2D rectangle = 
      new Rectangle2D.Double (
      20, 20, 200, 100);
    g2d.setColor (;
    g2d.setStroke (new BasicStroke(
      new float[] {2f}, 
    g2d.draw (rectangle);
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact