Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setAlignmentY not centering JLabel in BorderLayout

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!

like image 926
Jehu Avatar asked Jan 14 '12 18:01

Jehu


People also ask

How do you center a Jlabel in JPanel BorderLayout?

You just need to add your labels in a JPanel which uses a layout that aligns the labels at the center, like GridBagLayout does. Your first label will have gridx = 0 and gridy = 0 , the second label will have gridx = 0 and gridy = 1 .

What happens when adding a component to a BorderLayout If you do not specify the region in which the component should be placed?

Figure 7.5: BorderLayout with missing regions If the name is not "North", "South", "East", "West", or "Center", the component is added to the container but won't be displayed. Otherwise, it is displayed in the appropriate region.

What happens when more than one component is added to a particular region in a BorderLayout?

Note : Using BorderLayout manager, we can only add one component in a particular region. If we add more than one component in any region, only the last added component will be visible in that region.


1 Answers

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.

like image 94
Green Day Avatar answered Oct 29 '22 03:10

Green Day