我的问题是,我想在面板中画一条虚线。我可以这样做,但它也用虚线画出了我的边界。
有人能解释一下为什么吗?我使用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);
}
发布于 2014-02-24 21:36:50
您正在修改传递给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();
}
发布于 2015-03-31 22:10:09
另一种可能性是存储交换局部变量(Ex.颜色、笔触等...)并将它们重新设置为正在使用的图形。
类似于:
Color original = g.getColor();
g.setColor( // your color //);
// your drawings stuff
g.setColor(original);
这将适用于您决定对Graphics进行的任何更改。
https://stackoverflow.com/questions/21989082
复制相似问题