0

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);
    }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 2
    Is it an option to use a `BorderLayout`? – Progman Feb 19 '23 at 12:51
  • You do not add() components to a jframe that way jfrm.getContentPane().add(component , layout type). then jfrm.pack() then jfrm.setVisible(true) – Samuel Marchant Feb 19 '23 at 13:46
  • It is often much easier with jframe to set only one jpanel and set the gridbag layout to it then insert the required position components into the panel because jpanel has greater affinity for positioning of components than top windows. – Samuel Marchant Feb 19 '23 at 13:50
  • Oracle has a helpful tutorial, [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html). Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the [Laying Out Components Within a Container](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) section. – Gilbert Le Blanc Feb 23 '23 at 14:36

1 Answers1

0

You could anchor the first container in the WEST location

c.anchor = GridBagConstraints.WEST;
Reimeus
  • 158,255
  • 15
  • 216
  • 276