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); }
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.
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.
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.
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(); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With