Question

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.

Was it helpful?

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.

OTHER TIPS

That's not a real answer to your question but rather a suggestion: if you want to keep alignments across components then:

  • don't use borders
  • use only one panel for the whole dialog or frame
  • use a LayoutManager that ensures correct alignment (suggestion: DesignGridLayout, but there are other good LayoutManagers as well)
  • if you need to visually group components (the same way as a titled border), then introduce a row with a JLabel and a horizontal JSeparator (this one is a suggestion of Karsten Lentszch, from the JGoodies fame)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top