Not able to add 3 JPanels to a main panel

前端 未结 4 758
北荒
北荒 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: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();
      }
    }
    

提交回复
热议问题