在java中绘制虚线

2022-09-01 08:47:09

我的问题是我想在面板中画一条虚线。我能够做到这一点,但它也用虚线绘制了我的边框。

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

答案 1

您正在修改传递到 的实例,该实例也用于绘制边框。GraphicspaintComponent()

相反,请创建实例的副本并使用它来进行绘制: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();
}

答案 2

另一种可能性是存储交换局部变量中使用的值(例如颜色,笔触等),并将它们设置回使用时图形。

类似的东西:

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

// your drawings stuff

g.setColor(original);

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


推荐