6

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.

Gianmarco
  • 2,536
  • 25
  • 57
  • Take a look at [MatteBorder](http://docs.oracle.com/javase/7/docs/api/javax/swing/border/MatteBorder.html) and [How to use borders](http://docs.oracle.com/javase/tutorial/uiswing/components/border.html) for examples – MadProgrammer Oct 05 '12 at 00:48
  • http://docs.oracle.com/javase/tutorial/uiswing/components/border.html#custom – Matt Ball Oct 05 '12 at 00:49

3 Answers3

12

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);
    }
}
Timmos
  • 3,215
  • 2
  • 32
  • 40
  • Had difficulties getting this to work in Java 6. Had to define the Insets as well. See my post below – Olmstov Feb 08 '22 at 18:10
5

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

gobernador
  • 5,659
  • 3
  • 32
  • 51
  • 2
    This is a good answer, but please include that the mentioned method is in the JDK since Java 1.7. – Timmos Mar 07 '13 at 09:41
  • 2
    Also, the standard `Color` class implements `Paint`, so don't go nuts trying to parse the function signature. – Ti Strga Feb 14 '17 at 23:20
0

Using Java 6 I had issues with getting a custom AbstractBorder from Timmos solution (above) to work. The drawing would show odd artifacts like only a few pixels would draw sporadically. The insets needed to be defined and can be done by adding the following methods:

public Insets getBorderInsets(Component c)
{
    return new Insets(thickness, thickness, thickness, thickness);
}

public Insets getBorderInsets(Component c, Insets insets)
    insets.left = insets.right = insets.top = insets.bottom = thickness;
    return insets;
}

Where the thickness is whatever you want for your border. e.g. 1

Olmstov
  • 563
  • 7
  • 18