setAlignmentY not centering JLabel in BorderLayout

18,697

You were close, try this:

public static void main(String[] args)
{
    JFrame contentPane = new JFrame();
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new BorderLayout());

    JLabel label = new JLabel("This should be centered");
    label.setHorizontalAlignment(SwingConstants.CENTER);
    centerPanel.add(label, BorderLayout.CENTER);

    contentPane.add(centerPanel, BorderLayout.CENTER);
    contentPane.pack();
    contentPane.setVisible(true);
}

One of the many joys of GUI programming in Java. I'd rather poke my eye out if I'm being honest.

Share:
18,697
Jehu
Author by

Jehu

Updated on June 12, 2022

Comments

  • Jehu
    Jehu about 2 years

    new to java and brand new to the site. I have a JLabel added to the center panel of a BorderLayout. I would like the JLabel to be centered in the panel; setAlignmentX appears to work, but setAlignmentY does not (the label appears at the top of the panel). Here is the code:

    centerPanel = new JPanel();
    centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.Y_AXIS));
    
    JLabel label = new JLabel("This should be centered");
    label.setAlignmentX(Component.CENTER_ALIGNMENT);
    label.setAlignmentY(Component.CENTER_ALIGNMENT);
    centerPanel.add(label);
    
    contentPane.add(centerPanel, BorderLayout.CENTER);
    

    I have also tried label.setVerticalAlignment(CENTER);, to no avail. I've looked for an answer in the API and in the Java Tutorials, on this site, and through a google search. Thanks!

  • trashgod
    trashgod over 12 years
    +1 for alignment, also available in a constructor; -0.01 for eye trauma. :-)
  • Jehu
    Jehu over 12 years
    Is there a way to keep the BoxLayout, with the components that are added to the BoxLayout vertically centered in the center panel of the BorderLayout?
  • Green Day
    Green Day over 12 years
    have a read here: docs.oracle.com/javase/tutorial/uiswing/layout/box.html I appreciate it is painful but I think it will help you understand rather than just hacking away at the code
  • Jehu
    Jehu over 12 years
    Thanks for the direction, that was a very helpful read, and you're right, painful! I resolved the issue using vertical glue, and learned a few handy tricks along the way.