在java中绘制虚线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21989082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:52:50  来源:igfitidea点击:

Drawing dashed line in java

javagraphic

提问by Trung Bún

My problem is that I want to draw a dashed line in a panel, I'm able to do it but it draw my border in dashed line as well, which is oh my god!

我的问题是我想在面板中绘制一条虚线,我能够做到,但它也以虚线绘制了我的边框,天哪!

Can someone please explain why? I'm using paintComponent to draw and draw straight to the panel

有人可以解释为什么吗?我正在使用paintComponent来绘制并直接绘制到面板

this is the code to draw dashed line:

这是绘制虚线的代码:

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);
    }

采纳答案by Kevin Workman

You're modifying the Graphicsinstance passed into paintComponent(), which is also used to paint the borders.

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

Instead, make a copy of the Graphicsinstance and use that to do your drawing:

相反,制作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();
}

回答by Peter Walser

You modified the graphics context by setting a stroke, and subsequent methods such as paintBorder()use the same context and thus inherit all modifications you made.

您通过设置笔触修改了图形上下文,随后的方法(例如paintBorder()使用相同的上下文)并因此继承了您所做的所有修改。

Solution:clone the context, use it for painting and dispose it afterwards.

解决方案:克隆上下文,将其用于绘制并在之后处理它。

Code:

代码:

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

回答by Mário de Sá Vera

Another possibility would be to store the values used in swap local variables (Ex. Color , Stroke etc...) and set them back to the on use Graphics.

另一种可能性是存储交换局部变量(例如 Color 、 Stroke 等...)中使用的值,并将它们设置回使用时的 Graphics。

something like :

就像是 :

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

// your drawings stuff

g.setColor(original);

this will work for whatever change you decide to do to the Graphics.

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