开发者

Not able to add 3 JPanels to a main panel

I have 3 JPanels and I want to place them all in one JPanel. I used the GridBagLayout for the main panel. But only one panel is getting added. Why might this be?

    gblayout=new GridBagLayout();
    gbc=new GridBagConstraints();
    panel1Customizer();
    panel2customizer();
    panel3Customizer();
    setLayout(gblayout);
    gbc.fill=GridBagConstraints.HORIZONTAL;
    gbc.anchor=GridBagConstraints.NORTHWEST;
    gbc.weightx=1;
    gbc.weighty=1;
    gbc.gridheight=GridBagConstrain开发者_C百科ts.REMAINDER;
    add(panel1, gbc);
    add(panel2, gbc);
    gbc.gridwidth=GridBagConstraints.REMAINDER;
    add(panel3, gbc);

The customizer methods are ones which add items into these panels.


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜