在java中绘制虚线

Tru*_*Bún 25 java graphic

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

有人可以解释一下原因吗?我正在使用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);
    }
Run Code Online (Sandbox Code Playgroud)

Kev*_*man 37

您正在修改Graphics传入的实例paintComponent(),该实例也用于绘制边框.

相反,制作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();
}
Run Code Online (Sandbox Code Playgroud)

  • 每当您修改 Graphics 对象时。颜色等设置可能会通过其他绘画方法再次设置,但笔触等设置并不总是重置。不同的外观和感觉甚至可能会有所不同,所以安全总比后悔好。 (2认同)