setAlignmentY not centering JLabel in BorderLayout

Jehu picture Jehu · Jan 14, 2012 · Viewed 18.1k times · Source

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!

Answer

Green Day picture Green Day · Jan 14, 2012

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.