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 {
    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");

        JApplet applet = new DrawStrokeDemo();
        frame.setSize(new Dimension(400, 200));

This code snippet produce the following output:

Draw Stroke Demo

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply