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

55,196

Solution 1

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

Solution 2

So far the best method I've encountered that works with every type of component:
1. Create a new JPanel:

JPanel helperPanel = new JPanel();

2. Add the component (in this example submitButton) you wish to center horizontally to the JPanel :
helperPanel.add(submitButton);

3. Add the panel to your original panel (the one with the BoxLayout): outerPanel.add(helperPanel);

That's it! You could also set a maximum size on the helperPanel if you don't want the BoxLayout of the outerPanel to expand it.
If you're wondering why this works: the implicit layout manager of a JPanel is FlowLayout, which centers your elements automatically.

Share:
55,196
Roman
Author by

Roman

Updated on July 10, 2022

Comments

  • Roman
    Roman almost 2 years

    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?

  • Witold Kaczurba
    Witold Kaczurba over 7 years
    I tried that and noticed that all items had to have applied setAlignmentX(Component.CENTER_ALIGNMENT) to the same value of CENTER_ALIGNMENT. Applying it only to one JButton did not help. Also setHorizontalAlignment(SwingConstants.CENTER) did not help at all. Hope this is of a help to you.
  • Mark Jeronimus
    Mark Jeronimus about 3 years
    While it works with JLabel or JComboboxes individually, it doesn't work when combining those.
  • Mark Jeronimus
    Mark Jeronimus about 3 years
    I would instantiate the helperPanel with a new Borderlayout(), otherwise the components will be cut off when using the maximum size trick.