[英]Drawing dashed line in 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){
// 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();
}
另一种可能性是存储交换局部变量(例如 Color 、 Stroke 等...)中使用的值,并将它们设置回使用时的 Graphics。
就像是 :
Color original = g.getColor();
g.setColor( // your color //);
// your drawings stuff
g.setColor(original);
这将适用于您决定对图形进行的任何更改。
您通过设置笔触修改了图形上下文,随后的方法(例如paintBorder()
使用相同的上下文,从而继承您所做的所有修改。
解决方案:克隆上下文,将其用于绘制并在之后处理它。
代码:
// derive your own context
Graphics2D g2d = (Graphics2D) g.create();
// use context for painting
...
// when done: dispose your context
g2d.dispose();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.