Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java add a Dashed or dotted border to a JPanel

I am having problems with this thing: can I, in some way, add a dashed (or dotted, no matter) border to a JPanel?

I searched SO questions but seems that no one asked this before.

I'm wondering if is there any class to use. actually I am using:

myPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

Obviously this is a standard class that give only few standard borders, no one is useful for me.

like image 314
Gianmarco Avatar asked Oct 05 '12 00:10

Gianmarco


2 Answers

You're looking for BorderFactory.createDashedBorder(Paint).

like image 27
gobernador Avatar answered Oct 21 '22 05:10

gobernador


Starting from Java 7, you can use BorderFactory.createDashedBorder(Paint).

Prior to Java 7, you have to define this border yourself. Then you can use this self-written border:

private class DashedBorder extends AbstractBorder {
    @Override
    public void paintBorder(Component comp, Graphics g, int x, int y, int w, int h) {
        Graphics2D gg = (Graphics2D) g;
        gg.setColor(Color.GRAY);
        gg.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{1}, 0));
        gg.drawRect(x, y, w - 1, h - 1);
    }
}
like image 89
Timmos Avatar answered Oct 21 '22 05:10

Timmos