Search code examples
javaswinguser-interfacebordertitled-border

Remove space around title in TitledBorder


How can I remove space around title in TitledBorder? I mean this red border
red border

piece of code:

Font f = new Font(Font.DIALOG, Font.PLAIN, 14);
Map m = f.getAttributes();
m.put(TextAttribute.BACKGROUND, Color.yellow);
Font ff = new Font(m);
Border mb = BorderFactory.createMatteBorder(20, 0, 0, 0, Color.yellow);
Border test = BorderFactory.createEmptyBorder(-2,-2,-2,-2);
Border mb6 = BorderFactory.createTitledBorder(mb, "Title", TitledBorder.CENTER, TitledBorder.TOP, ff, Color.DARK_GRAY);
mb6 = BorderFactory.createCompoundBorder(test, mb6);
Border mb2 = BorderFactory.createMatteBorder(1, 0, 0, 0, Color.gray);
mb2 = BorderFactory.createCompoundBorder(test,mb2);
Border mb3 = BorderFactory.createCompoundBorder(mb6, mb2);
Border mb4 = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray);
Border mb5 = BorderFactory.createCompoundBorder(mb4, mb3);
modeSetPanel.setBackground(Color.red);
modeSetPanel.setBorder(mb5);

Solution

  • If you do not care about borders, you could add a JPanel inside your Settings Tab panel. In this JPanel you add another, with BorderLayout. Inside the one with the BorderLayout add two JPanels: The north one is with yellow background and the center one is with a red background. Just add a JLabel that says "Title" to the yellow JPanel and your controls to the red one.

    This red border around the label is gone.

    Here is an example without any borders and in the Nimbus look & feel:

    Sample...