Search code examples
javaswingjframejtextfieldgrid-layout

How to fix JPanel with Grid that occupies full width of frame?


I'm working on a layout for a simple login screen. I am using GridLayout in order to manipulate elements, but have came across an issue, It occupies full frame width like this:

enter image description here

Where as I want it to be with a fixed position and width,height and be vertically, horizontally centered inside a frame, but not occupy it's full size. Possibly make Username and Password labels occupy less space so text fields are actually closer to them. I tried setting main size of my panel like .setMaximumSize(Dimension (200, 150));

But it doesn't seem to work.

        //Create the frame.
        JFrame frame = new JFrame("Online Shop");
        JPanel mainPanel = new JPanel();
        JPanel usernamePanel = new JPanel();
        JPanel passwordPanel = new JPanel();
        JPanel buttonPanel = new JPanel();

        JButton loginButton = new JButton("Login");
        loginButton.setMaximumSize(new Dimension(100, 50));
        JTextField username = new JTextField();
        JLabel usernameLabel = new JLabel("Username");
        JPasswordField password = new JPasswordField();
        JLabel passwordLabel = new JLabel("Password");

        //Panel
        frame.setContentPane(mainPanel);

        usernamePanel.setLayout(new GridLayout(1,2));
        usernamePanel.add(usernameLabel);
        usernamePanel.add(username);

        passwordPanel.setLayout(new GridLayout(1,2));
        passwordPanel.add(passwordLabel);
        passwordPanel.add(password);

        mainPanel.setLayout(new GridLayout(3, 1));
        mainPanel.add(usernamePanel);
        mainPanel.add(passwordPanel);
        mainPanel.add(loginButton);

        //Event Listeners
        frame.addWindowListener(new MyWindowListener());
        loginButton.addActionListener(new MyActionListener());

        //Sizes, Positioning
        frame.setSize(720, 480);
        frame.setLocationRelativeTo(null);

        //Show Frame
        frame.setVisible(true);

Solution

  • frame.setSize(720, 480);
    

    Don't use the setSize() method.

    Instead use:

    frame.pack();
    

    Also use:

    JTextField username = new JTextField(10);
    

    To give the text fields a preferred number of characters.

    Now when the frame is made visible the components will be displayed at their preferred size and the frame will be sized appropriately to fit the components.

    If you want a little extra space between the components and the frame then you can do:

    mainPanel.setBorder( new EmptyBorder(20, 20, 20, 20) );