在java中绘制虚线

我的问题是我想在一个面板中绘制一条虚线,我能够做到这一点,但它也以虚线画出我的边框,这是我的天啊!

有人可以解释一下原因吗? 我正在使用paintComponent直接绘制并绘制到面板

这是绘制虚线的代码:

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); } 

您正在修改传递给paintComponent()Graphics实例,该实例也用于绘制边框。

相反,制作Graphics实例的副本并使用它来绘制图形:

 public void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2){ //creates 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); g2d.drawLine(x1, y1, x2, y2); //gets rid of the copy g2d.dispose(); } 

您通过设置笔划来修改图形上下文,后续方法(如paintBorder()使用相同的上下文,从而inheritance您所做的所有修改。

解决方案:克隆上下文,使用它进行绘制并在之后进行处理。

码:

 // derive your own context Graphics2D g2d = (Graphics2D) g.create(); // use context for painting ... // when done: dispose your context g2d.dispose(); 

另一种可能性是存储交换局部变量中使用的值(例如Color,Stroke等…)并将它们设置回使用中的Graphics。

就像是 :

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

这将适用于您决定对Graphics进行的任何更改。