22

I want to add padding to some JPanels. I found this answer: https://stackoverflow.com/a/5328475/1590323

It worked fine for a panel without a border. But how do I do it for a panel that already has a border? (A TitledBorder in this case)

I tried:

JPanel mypanel = new MyPanel(); // Panel that I am going to add a TitledBorder to, but needs padding
mypanel.setBorder(new EmptyBorder(10,10,10,10));
JPanel mypanel_container = new JPanel();
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), "My panel");
border.setTitleJustification(TitledBorder.LEADING);
mypanel_container.setBorder(border);
mypanel_container.add(mypanel);
this.add(mypanel_container);

(In short: Adding an EmptyBorder to the panel that should have a TitledBorder, then make another panel with the TitledBorder and add the first panel to that, and then use that panel)

But then I got way too large padding that ignored the contructor values of the EmptyBorder.

So how do I add padding to a JPanel with a graphical border?

Community
  • 1
  • 1
jobukkit
  • 2,490
  • 8
  • 26
  • 41
  • 2
    +1, to the hard work you had done before posting the question :-) though, as stated previously this will come in some time – nIcE cOw Jul 29 '13 at 15:16

1 Answers1

38

You can take a look at CompoundBorder.

A composite Border class used to compose two Border objects into a single border by nesting an inside Border object within the insets of an outside Border object. For example, this class may be used to add blank margin space to a component with an existing decorative border:

Border border = comp.getBorder();
Border margin = new EmptyBorder(10,10,10,10);
comp.setBorder(new CompoundBorder(border, margin));

Of course, you can also use BorderFactory#createCompoundBorder(border, margin).

XP1
  • 6,910
  • 8
  • 54
  • 61
NiziL
  • 5,068
  • 23
  • 33