setAlignmentX(CENTER_ALIGNMENT) does not center boxLayout in JFrame

user2211678 picture user2211678 · Aug 9, 2014 · Viewed 11k times · Source

I want to keep my two JLabel text have Left alignment and at the same time place my boxLayout in the center of the JFrame.

I tried setAlignmentX(CENTER_ALIGNMENT) on my boxlayout panel but it's not placing my boxlayout in the center.

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GuiTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private JLabel jLabelOne = new JLabel();    
    private JLabel jLabelTwo = new JLabel();
    private JPanel panel = new JPanel();
    private BoxLayout boxLayout = new BoxLayout(panel,BoxLayout.Y_AXIS);
    public GuiTest() {

        jLabelOne.setAlignmentX(LEFT_ALIGNMENT);
        jLabelTwo.setAlignmentX(LEFT_ALIGNMENT);

        jLabelOne.setText("This is text one");
        jLabelTwo.setText("This is text two");
        panel.setLayout(boxLayout);
        panel.add(jLabelOne);
        panel.add(jLabelTwo);

        panel.setAlignmentX(CENTER_ALIGNMENT);
        add(panel);
        pack();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(1024,768);
        setLocationRelativeTo(null);   
        setVisible(true);
    }

    public static void main(String args[]) {
        new GuiTest();
    }
}

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Aug 9, 2014

This won't achieve anything I believe:

panel.setAlignmentX(CENTER_ALIGNMENT);

because you're adding the panel to the JFrame's contentPane, a Container that uses BorderLayout, and are in fact adding it in a default way, meaning BorderLayout.CENTER.

Consider giving the contentPane a GridBagLayout, and adding the panel JPanel in a default way, which should center it. This will only be seen if its preferred size is smaller than that JFrame's contentPane.