Jason S
Jason S

Reputation: 189676

JLabel horizontal positioning not working as expected

Here's a JFrame which I intended to show with a series of JLabels with the following properties:

But I get this instead:

enter image description here

The blue text, stacked vertically, green border work OK but the white background and centered horizontally do not. I also would have thought the labels would span the entire width of the JPanel.

What am I doing wrong?


edit: Missed this question about background color. So my remaining question is about BoxLayout and the positioning of components in the other axis.


import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class BoxLayoutLabelsTest extends JFrame
{
    public BoxLayoutLabelsTest(String title)
    {
        super(title);
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        addLabel(panel, "Hydrogen");
        addLabel(panel, "Helium");
        addLabel(panel, "Lithium");
        addLabel(panel, "Beryllium");
        addLabel(panel, "Boron");

        setContentPane(panel);
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    static private void addLabel(JPanel panel, String text) {
        JLabel label = new JLabel(text);
        label.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        label.setBackground(Color.WHITE);
        label.setForeground(Color.BLUE);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(label);
    }

    public static void main(String[] args) {
        new BoxLayoutLabelsTest("BoxLayoutLabelsTest").setVisible(true);
    }

}

Upvotes: 3

Views: 5736

Answers (1)

MockerTim
MockerTim

Reputation: 2483

Add the following line into addLabel():

label.setAlignmentX(CENTER_ALIGNMENT);

See How To Use BoxLayout for complete example.

Added later:

I've found straightforward solution:

label.setMaximumSize(new Dimension(200, 200));
//label.setAlignmentX(CENTER_ALIGNMENT);//aligns label itself
label.setHorizontalAlignment(SwingConstants.CENTER);//aligns text inside the label

This also works, but your solution with BorderLayout seems more appropriate.

Upvotes: 4

Related Questions