Search code examples
javaswingtitled-border

Removing the spacing around a TitledBorder


A javax.swing.border.TitledBorder introduces a spacing of 2 pixels around the edges of the border. This is quite annoying because it breaks the alignment with the components around.

How do you remove this spacing?

I'm looking for a solution that works for any look and feel.


Solution

  • Unfortunately this edge width is hardcoded in TitledBorder class. So you can not remove this spacing.

    public class TitledBorder extends AbstractBorder
    {
        //...
    
        // Space between the border and the component's edge
        static protected final int EDGE_SPACING = 2;
    }
    

    But you can try to extend this class (override methods "void paintBorder(Component, Graphics, int, int, int, int)" or may be "Insets getBorderInsets(Component, Insets)") or implement your own border from scratch.