I want to add padding to some JPanel
s. 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?
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)
.