How do I create a dashed stroke in Java 2D?

package org.kodejava.awt.geom;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;

public class DrawDashedStroke extends JComponent {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Dashed Stroke Demo");
        frame.getContentPane().add(new DrawDashedStroke());
        frame.setSize(new Dimension(420, 250));

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        float[] dash = {10.0f, 5.0f, 3.0f};

        // Creates a dashed stroke
        Stroke dashed = new BasicStroke(2.0f, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);

        g2.draw(new RoundRectangle2D.Double(50, 50, 300, 100, 10, 10));

This code snippet produce the following output:

Draw 2D Dashed Stroke

Draw 2D Dashed Stroke

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.