Not able to add 3 JPanels to a main panel

前端 未结 4 761
北荒
北荒 2021-01-24 15:09

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?



        
相关标签:
4条回答
  • 2021-01-24 15:15

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

    0 讨论(0)
  • 2021-01-24 15:17

    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 讨论(0)
  • 2021-01-24 15:21

    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();
      }
    }
    
    0 讨论(0)
  • 2021-01-24 15:29

    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

    0 讨论(0)
提交回复
热议问题