Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing dashed line in java

Tags:

java

graphics

My problem is that I want to draw a dashed line in a panel. I'm able to do it, but it drew my border in a dashed line as well.

Can someone please explain why? I'm using paintComponent to draw and draw straight to the panel.

This is the code to draw a dashed line:

public void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2){         Graphics2D g2d = (Graphics2D) g;         //float dash[] = {10.0f};         Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);         g2d.setStroke(dashed);         g2d.drawLine(x1, y1, x2, y2);     } 
like image 896
Trung Bún Avatar asked Feb 24 '14 13:02

Trung Bún


People also ask

What is dashed line in drawing?

Solid Versus Dashed or Dotted Lines The first and most basic rule of lines in design drawings is that solid lines indicate visible or “real” objects or surfaces, while anything drawing with dots and/or dashes indicates something that is unseen or “hidden” from view.

How do you draw a line in Java?

Java Applet | Draw a line using drawLine() method x1 – It takes the first point's x coordinate. y1 – It takes first point's y coordinate. x2 – It takes second point's x coordinate. y2 – It takes second point's y coordinate.

What is stroke in Java?

The Stroke interface allows a Graphics2D object to obtain a Shape that is the decorated outline, or stylistic representation of the outline, of the specified Shape . Stroking a Shape is like tracing its outline with a marking pen of the appropriate size and shape.


2 Answers

You're modifying the Graphics instance passed into paintComponent(), which is also used to paint the borders.

Instead, make a copy of the Graphics instance and use that to do your drawing:

public void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2){    // Create a copy of the Graphics instance   Graphics2D g2d = (Graphics2D) g.create();    // Set the stroke of the copy, not the original    Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,                                   0, new float[]{9}, 0);   g2d.setStroke(dashed);    // Draw to the copy   g2d.drawLine(x1, y1, x2, y2);    // Get rid of the copy   g2d.dispose(); } 
like image 180
Kevin Workman Avatar answered Sep 28 '22 20:09

Kevin Workman


Another possibility would be to store the values used in swap local variables (Ex. Color , Stroke etc...) and set them back to the on use Graphics.

something like :

Color original = g.getColor(); g.setColor( // your color //);  // your drawings stuff  g.setColor(original); 

this will work for whatever change you decide to do to the Graphics.

like image 28
Mário de Sá Vera Avatar answered Sep 28 '22 22:09

Mário de Sá Vera