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

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

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