Search code examples
javaswinglayoutcomponentslayout-manager

Java - How to center components horizontally, and stack them vertically?


I am writing a application that will take user information such as the name, email, password. To get the user information I am using JTextFields. I would like to have all the components in the center of the screen vertically and horizontally, and also have the components stack on top of each other one after the other like so: Expected Design

Like you would see on a website. Currently I am using a JPanel inside a JFrame, the JPanel has a BoxLayout with a BoxLayout.Y_AXIS. Here is my code:

public class RegisterLayout extends Layout {

    @Override
    public void init() {
        this.setBackground(Utilities.babyBlueish);
        this.setBorder(BorderFactory.createTitledBorder("Register Now!"));
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    }

    @Override
    public void addComponents() {
        
        JTextField fName = new JTextField("Enter Your Full Name");
        fName = Utilities.designTextField(fName);
        
        JButton submit = new JButton("Submit");
        submit = Utilities.designButton(submit);
        submit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                
            }
            
        });
        
        this.add(fName);
        this.add(submit);
    }

}

Both init() and addComponents() are called when the JPanel is added to the JFrame's content pane. "RegisterLayout extends Layout" and "Layout extends JPanel". Currently with the code I have my program looks like this: Current Design. As you can see the JTextField is off center with the screen horizontally and as a whole it is not centered vertically.

If anyone could help I would appreciate it. If you need further details please let me know.


Solution

  • There are multiple ways this layout could be coded. This is one way.

    Break the sections of the GUI into logical units, 'a column of text fields', 'an area for form controls' etc., then provide a container with a suitable layout for each.

    enter image description here

    In this GUI mock-up:

    • The purple area has a border layout, with the two green areas appearing in the center and page end constraints.
    • The first green area at the top would be a grid bag layout, to center (horizontally and vertically) the ..
    • Single column grid layout of text fields, bordered in orange.
    • The 2nd green bordered area could be another grid bag layout, or if only horizontal centering was needed, a flow layout.

    Suitable borders (e.g. an empty border, which is invisible) could be applied to the containers for white space.