Search code examples
javaswingjlabellayout-managerboxlayout

JLabel does not align the text in the center


Is there anything wrong in this code?

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel lab = new JLabel();
lab.setHorizontalAlignment(SwingConstants.CENTER);
lab.setText("TESET");
panel.add(lab);
frame.getContentPane().add(BorderLayout.NORTH,panel);
frame.setVisible(true);
frame.pack();

Solution

  • In the future, a proper SSCCE should include the main() method and the import statements so we don't need to do any extra work to test your code.

    //lab.setHorizontalAlignment(SwingConstants.CENTER);
    lab.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    

    Horizontal alignment is for the text within the bounds of the label.

    AlignmentX is for the component alignment within the parent container.