Home > Blockchain >  Trying to use a GridBagLayout to manage JPanels in Java
Trying to use a GridBagLayout to manage JPanels in Java

Time:04-30

I am currently making my first steps with GUIs and am right now just trying to make a JFrame with two JPanel containers according to my work of art here:

https://img.codepudding.com/202204/b753937999644747bb4835b555c6fd42.png

I chose the GridBagLayout since I want it to be resizeable later but keep the given proportions, yet I'm having a hard time understanding how all of this works.

My current code looks like this:

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

public class MyFrame extends JFrame {

     private JPanel contentPane;
         
    public JPanel getContentPane() {
        return contentPane;
    }

    public void setContentPane(JPanel contentPane) {
        this.contentPane = contentPane;
    }

    public MyFrame (){

        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.gridheight = 3;
        JPanel blue = new JPanel();
        blue.setBackground(Color.BLUE);

        contentPane.add(blue, gbc);


        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 3;
        JPanel gruen = new JPanel();
        gruen.setBackground(Color.green);
        contentPane.add(gruen, gbc);

        this.setPreferredSize(new Dimension(630, 650));
        this.pack();
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setContentPane(contentPane);
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}

Which gives me this empty window:

https://img.codepudding.com/202204/e091a3826cdd47c4a30bee94dc66551f.png

If someone could tell me what I'm doing wrong that would be great.

CodePudding user response:

1. First of all, you need to remove this:

public JPanel getContentPane() {
    return contentPane;
}

public void setContentPane(JPanel contentPane) {
    this.contentPane = contentPane;
}

because you basically override the base logic of JFrame, hence you may (and likely will) break something.

2. The second thing is that putting component to the grid cells with constraints does not automatically stretch them across the area. If to refer to the enter image description here

  • Related