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

package org.kodejava.example.awt.geom;

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

public class DrawStrokeDemo extends JApplet {
    @Override
    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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new DrawStrokeDemo();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 200));
        frame.setVisible(true);
    }
}

This code snippet produce the following output:

Draw Stroke Demo

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.