2

Is there an easier way to just remove the horizontal space in front of the first component in FlowLayout?

This is basically what my code looked like :

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
JLabel label1 = new JLabel("Hello");
JLabel label2 = new JLabel("Goodbye");
panel.add(label1);
panel.add(label2);

What I'm seeing is that there is a horizontal gap between label1 and label2, however, it also added spacing in front of label1. My current solution is remove the horizontal gap and add an EmptyBorder to label2 to fix this.

But for situations with many components, I am wondering if there is a more easy and efficient way to do something this simple?

ghost013
  • 97
  • 1
  • 10
  • What version of JPanel do you use? I am wondering because you use 3 parameters in your constructor (compare: http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html). – mrbela Jan 29 '15 at 18:26
  • 1
    Generally, people want the gap in front of the first component. It looks better. – Gilbert Le Blanc Jan 29 '15 at 18:36
  • @user2438518 Sorry, fixed the code. Gilbert Le Blanc: Yes, but I need to have the labels aligned to the left which is why I need to remove the spacing. – ghost013 Jan 29 '15 at 18:55
  • If you want column alignment for many labels and fields, you use the GridBagLayout. – Gilbert Le Blanc Jan 29 '15 at 19:08

2 Answers2

9

You can use a horizontal BoxLayout:

panel.add( label1 );
panel.add( Box.createHorizontalStrut(5) );
panel.add( label2 );

Or you can add an EmptyBorder to the panel, instead of the labels:

panel.setBorder( BorderFactory.createEmptyBorder(0, -5, 0, 0) );
camickr
  • 321,443
  • 19
  • 166
  • 288
0

Try

new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));

The second parameter stands for a horizontal gap. So maybe this fix your problem.

You can also look:

mrbela
  • 4,477
  • 9
  • 44
  • 79
  • I've tried that and the issue is that is adds a gap to both sides, when I really one a gap on the left of the first label, then gaps on both sides any other labels. – ghost013 Feb 02 '15 at 22:49