setAlignmentX(CENTER_ALIGNMENT) does not center boxLayout in JFrame

11,586

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.

Share:
11,586
user2211678
Author by

user2211678

Updated on June 26, 2022

Comments

  • user2211678
    user2211678 about 2 years

    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();
        }
    }