在java中绘制虚线

在java中绘制虚线

本文介绍了在java中绘制虚线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

有人可以解释一下原因吗?我正在使用paintComponent直接绘制并绘制到面板

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

这是绘制虚线的代码:

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


推荐答案

你正在修改 Graphics 实例传递到 paintComponent(),它也用于绘制边框。

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

相反,复制 Graphics 实例并使用它来绘图:

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

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

这篇关于在java中绘制虚线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:52