How do I define stroke when drawing a shape in Java 2D?

package org.kodejava.example.geom;

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

public class DrawStrokeDemo extends JComponent {
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        float[] strokes = {1, 2, 3, 4, 5, 6};
        for (float stroke : strokes) {
            g2.setStroke(new BasicStroke(stroke));
            g2.draw(new Line2D.Float(50, stroke * 20, 350, stroke * 20));

    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Stroke Demo");
        frame.getContentPane().add(new DrawStrokeDemo());
        frame.setSize(new Dimension(420, 200));

This code snippet produce the following output:

Draw Stroke Demo


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ā˜• or šŸµ

Leave a Reply