123

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?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
Connor
  • 1,943
  • 5
  • 16
  • 13

4 Answers4

268

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));
Nateowami
  • 1,005
  • 16
  • 23
Julien Vermillard
  • 2,945
  • 1
  • 18
  • 18
  • 55
    or you can have some extra padding arround the existing border: `p.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder()));` – Synox Apr 22 '13 at 08:42
  • What happens when the Window is resized? This solution is not good then is it? – Andrew S Apr 02 '14 at 08:14
  • @Synox Legend indeed! Note that you can put EmptyBorder as last parameter for internal padding – Hunter S Mar 17 '18 at 23:11
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.

jzd
  • 23,473
  • 9
  • 54
  • 76
  • 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. – Connor Mar 16 '11 at 16:42
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

Riduidel
  • 22,052
  • 14
  • 85
  • 185
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);
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
Demetrio
  • 11
  • 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](https://stackoverflow.com/help/how-to-answer). – moken Apr 08 '23 at 11:47