Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add padding to a JPanel with a border

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?

like image 447
stommestack Avatar asked Jul 29 '13 13:07

stommestack


People also ask

How do I change the layout of a JPanel?

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.

How do I set margins in JFrame?

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 .


1 Answers

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).

like image 196
NiziL Avatar answered Oct 23 '22 23:10

NiziL