JPanel Padding in Java
Asked Answered
H

4

124

I have a formatting question for my Java swing application. It should be fairly straightforward, but I am having difficulty finding any aid (Every topic seems to be regarding removing any default padding in JPanel).

The text in my various JPanels hug the sides and top, touching the colored borders: how can I add padding?

Hemimorphite answered 16/3, 2011 at 16:27 Comment(0)
R
271

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));
Romilly answered 16/3, 2011 at 16:33 Comment(3)
or you can have some extra padding arround the existing border: p.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder()));Brunei
What happens when the Window is resized? This solution is not good then is it?Symphysis
@Brunei Legend indeed! Note that you can put EmptyBorder as last parameter for internal paddingThunderstone
M
4

When you need padding inside the JPanel generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel.

Merrick answered 16/3, 2011 at 16:33 Comment(1)
Adding padding to the layout manager (In my case, GridLayout) adds padding in between the adjacent panels, but not within an individual panel. But a border will do, thank you for the help.Hemimorphite
G
3

I will suppose your JPanel contains JTextField, for the sake of the demo.

Those components provides JTextComponent#setMargin() method which seems to be what you're looking for.

If you're looking for an empty border of any size around your text, well, use EmptyBorder

Generalize answered 16/3, 2011 at 16:45 Comment(0)
H
1
JPanel p=new JPanel();  
GridBagLayout layout=new GridBagLayout(); 
p.setLayout(layout); 
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.HORIZONTAL; 
gbc.gridx=0;   
gbc.gridy=0;   
p2.add("",gbc);
Historied answered 8/10, 2015 at 20:2 Comment(1)
Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Abstractionism

© 2022 - 2024 — McMap. All rights reserved.