If anyone has an idea how to draw a dashed line using Java?? Graphics class seems to be not support a function for this.

Thanks

You need to call Graphics2D.setStroke(Stroke) method before drawing a line. You will need to create a Stroke first - use the BasicStroke class for now. Also, don't forget to reset the stroke after you have drawn your line.

commented: Concise and correct. +9

thanx a lot. Ill checking in that way

If anyone has an idea how to draw a dashed line using Java?? Graphics class seems to be not support a function for this.

Thanks

@diasmvds

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

public class Stroke1 extends JFrame {

    Stroke drawingStroke = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
    Line2D line = new Line2D.Double(20, 40, 100, 40);

    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setStroke(drawingStroke);
        g2d.draw(line);
    }

    public static void main(String args[]) {
        JFrame frame = new Stroke1();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setSize(200, 100);
        frame.setVisible(true);
    }
}

You can vary the thinkness of the line and also the width of each dash.

Hope it answers u'r requirement

Hi sanaulla123,

At DaniWeb we try to guide those asking for help rather than just blurting out the answer for them to copy. Please repect this in future :)

Hi sanaulla123,

At DaniWeb we try to guide those asking for help rather than just blurting out the answer for them to copy. Please repect this in future :)

Whats there is giving a code. U had mentioned that one can use BasicStroke and i just gave a code. And for your information even i didnot know about it b4 posting it here.

What I'm trying to say is that it's not a good idea to post a chunk of code in answer to someone's question. Instead, try giving clues or pointers to what they need to do and let them code it themselves. They learn better that way and also don't feel like a cheat for blatantly copying your code.

What I'm trying to say is that it's not a good idea to post a chunk of code in answer to someone's question. Instead, try giving clues or pointers to what they need to do and let them code it themselves. They learn better that way and also don't feel like a cheat for blatantly copying your code.

Yeah you are right. U can see i am new to Daniweb and have been posting from yesterday. I actually had a hard time coding for Graphics in Java so thought of helping with the code. Never mind i will try not posting code again. And i suppose the code solves the question :)

commented: nice code sanaulla...keep posting on daniweb, its a great forum +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.