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!
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With