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 set a panel's layout manager using the JPanel constructor. For example: JPanel panel = new JPanel(new BorderLayout()); After a container has been created, you can set its layout manager using the setLayout method.
The correct way to do it would be to extend a JFrame and then override the getInsets() method. Show activity on this post. you can create a main JPanel and insert everything else into it. Then you can use BorderFactory to create EmptyBorder or LineBorder .
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With