在Java中绘制虚线

34

我的问题是我想在一个面板中画一条虚线。我已经能够做到了,但它也把我的边框画成了虚线。

有人可以解释一下为什么吗?我正在使用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);
    }
3个回答

48

你正在修改传递到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();
}

我有一个快速的问题:在哪种情况下我需要克隆当前的图形?显然,不需要克隆每个图形实例 :) - Trung Bún
2
每当您修改Graphics对象时,诸如颜色之类的设置可能会被其他绘图方法再次设置,但是像笔画之类的设置并不总是重置。 甚至在不同的外观和感觉之间可能会有所不同,所以最好小心谨慎。 - Kevin Workman

3
另一个可能的方法是将交换中使用的值存储在本地变量中(例如,颜色、笔画等),并在使用图形后将其设置回去。类似以下内容:

如下所示:

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

// your drawings stuff

g.setColor(original);

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

2

您通过设置描边方式修改了图形上下文,接下来的方法(比如paintBorder())将使用相同的上下文,因此继承您所做的所有修改。

解决方案: 克隆上下文,用于绘制后立即释放。

代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接