JavaCoder
JavaCoder

Reputation: 49

Creating vertical space between JLabels not going as expected

I want to create a vertical space between JLabels. This is my code:

    JPanel label = new JPanel(new FlowLayout(FlowLayout.LEFT));
    label.add(Box.createVerticalStrut(50));
    label.add(label1);
    label.add(Box.createHorizontalStrut(50));
    label.add(label2);
    label.add(Box.createVerticalStrut(50));
    label.add(label3);
    label.add(Box.createHorizontalStrut(50));
    label.add(label4);

I want to have the equal vertical space between each JLabel, however, it gets weird when I adjust the Box.createHorizontalStrut(50) Does anyone know why? The FlowLayout is done to position the JLabels to the left of the panel. In accordance with this, I want to position some of the JLabels in the center (hence the horizontal movement), is there another way to do it by the FlowLayout?

Thanks.

Upvotes: 0

Views: 451

Answers (1)

camickr
camickr

Reputation: 324147

I want to create a vertical space between JLabels

Then you should probably use a BoxLayout. Read the section from the Swing tutorial on How to Use BoxLayout for working examples.

The FlowLayout is done to position the JLabels to the left of the panel. In accordance with this

Then you can use setAlignmentX(0.0f) on each of the labels. The BoxLayout will then align the labels to the left.

I want to position some of the JLabels in the center

I believe this is the default value for the alignment of the label (each component is different) so you don't have to do anything. But if you want to make sure you can always use setAlignment(0.5f) on the label.

Upvotes: 2

Related Questions