Not able to add 3 JPanels to a main panel

╄→尐↘猪︶ㄣ 提交于 2019-12-02 07:11:45

I am not sure but I think you need to add a GridBagConstraints to your GridBagLayout. Try look at this site to get the idea on how to work with GridBagLayout: link

Or maybe just use another Layout for your JFrame, maybe BorderLayout or GridLayout to arrange your Panels correctly

You should change gbc.gridx and/or gbc.gridy to be different for each panel

you have to read How to Use GridBagLayout, examples for that here and GridBagConstraints, change your gbc.fill=GridBagConstraints.HORIZONTAL;, if you have problem(s) with JComponent's Size then add setPreferedSize(); for example

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

public class GBLFillBoth extends JFrame {
    private static final long serialVersionUID = 1L;

  public GBLFillBoth() {
    JPanel panel = new JPanel();
    GridBagLayout gbag = new GridBagLayout();
    panel.setLayout(gbag);
    GridBagConstraints c = new GridBagConstraints();
    JButton btn1 = new JButton("One");
    c.fill = GridBagConstraints.BOTH;
    //c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor=GridBagConstraints.NORTHWEST;
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 0.5;
    c.weighty = 0.5;
    panel.add(btn1, c);
    JButton btn2 = new JButton("Two");
    c.gridx++;
    panel.add(btn2, c);
    //c.fill = GridBagConstraints.BOTH;
    JButton btn3 = new JButton("Three");
    c.gridx = 0;
    c.gridy++;
    c.gridwidth = 2;
    panel.add(btn3, c);
    add(panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  }

  public static void main(String[] args) {
        GBLFillBoth gBLFillBoth = new GBLFillBoth();
  }
}

You might consider using a MigLayout instead, the code is much simpler:

panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(new MigLayout("fill, wrap 3"));

add(panel1, "grow");
add(panel2, "grow");
add(panel3, "grow");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!