SetAlignmentY does not center JLabel in BorderLayout

new for java and new for the site. I have a JLabel added to the central panel of BorderLayout. I would like JLabel to be focused in the panel; setAlignmentX seems to work, but setAlignmentY does not (a 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 also tried label.setVerticalAlignment (CENTER); to no avail. I searched for the answer in the API and in the Java tutorials, on this site and in a Google search. Thank you

+7
source share
2 answers

you were close, try the following:

 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 cry out if I'm honest

+17
source

I tried to vertically align JButton , but I had a problem with stretching. After grumbling, I found this to work:

 JPanel jpTop = new JPanel(new BorderLayout()); jbStop = new JButton("Cancel"); JPanel extraPanel = new JPanel(); extraPanel.setLayout(new BoxLayout(extraPanel, BoxLayout.X_AXIS)); extraPanel.setAlignmentY(Component.CENTER_ALIGNMENT); extraPanel.add(jbStop); jpTop .add(extraPanel, BorderLayout.EAST); 

Of course, this works for JLabel as well.

0
source

All Articles