How to center elements in the BoxLayout using center of the element?

Roman picture Roman · Apr 1, 2010 · Viewed 48.8k times · Source

I use outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS)); and then I add elements (for example JLabels, JButtons) to the outputPanel. For example: outputPanel.add(submitButton);.

I see that all added elements are "centered". It is good, because I do want my elements to be in the center. When I write "center" I mean "equal distance from left and right". But the problem is that the left part of the element is put into the center. And I want to have center of elements to be put into the center. How can I get this behavior?

Answer

Roman picture Roman · Apr 1, 2010

The problem can be solved by using myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);. It works with JLabel, JButton and JRadioButton.