Location of Java Swing components

79 Views Asked by At

I cannot correctly position the components on the form using GridBagLayout. I have tried different variations, but the components are still in the center of the screen.

What I have at the moment enter image description here

What I want enter image description here

package View;

import javax.swing.*;
import java.awt.*;

public class Frame extends JFrame {
    private JPanel jPanelLeft = new JPanel();
    private JPanel jPanelRight = new JPanel();

    public Frame(){
        setTitle("SCHOOLLLLLLL");
        setSize(new Dimension(400,350));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        jPanelLeft.setBackground(Color.BLACK);
        jPanelRight.setBackground(Color.RED);
        jPanelLeft.add(new JButton("Click on me"));

        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 1;
        c.weighty = 1;
        c.gridx = 0;
        c.gridy = 0;
        c.fill = GridBagConstraints.VERTICAL;

        add(jPanelLeft, c);

        c.weightx = 1;
        c.weighty = 1;
        c.gridx = 1;
        c.gridy = 0;
        c.fill = GridBagConstraints.CENTER;
        
        add(jPanelRight, c);

        setVisible(true);
    }
}
1

There are 1 best solutions below

0
Reimeus On

You could anchor the first container in the WEST location

c.anchor = GridBagConstraints.WEST;