12

How can I keep a JLabel from displaying flush against the side of the frame? I have the same problem when using GridLayout or BoxLayout.

Here's an example where this happens:

JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(new JLabel("Hello World"));

CSS has the concept of margins and padding. Does Java have similar?

I still want Left justified but with a few pixels of space between the edge and the label.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alison
  • 5,630
  • 4
  • 18
  • 26

2 Answers2

21

You could set an empty border for the JLabel to move the component over a few pixels from the left edge:

label.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

For centered labels, try this:

content.add(new JLabel("Hello World", JLabel.CENTER));

If you're using Box, you can add space by calling,(on a vertical box):

content.add(Box.createVerticalStrut(height));
content.add(new JLabel("Hello World"));

Or for horizontal:

content.add(Box.createHorizontalStrut(width));
Mordechai
  • 15,437
  • 2
  • 41
  • 82