How to use GridBagConstraints to create the layout?

后端 未结 3 1068
傲寒
傲寒 2021-01-14 23:40

I want to layout my JPane like so:

-------
|     |
|     |
|     |
-------
|     |
-------

This way, the top section is bigger/taller than

3条回答
  •  遥遥无期
    2021-01-15 00:15

    not sure from your question, maybe will help you Top at 70%, Bottom at 30%

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class BorderPanels extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        public BorderPanels() {
            getContentPane().setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            JPanel panel1 = new JPanel();
            Border eBorder = BorderFactory.createEtchedBorder();
            panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "70pct"));
            gbc.gridx = gbc.gridy = 0;
            gbc.gridwidth = gbc.gridheight = 1;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            gbc.weightx = gbc.weighty = 70;
            getContentPane().add(panel1, gbc);
            JPanel panel2 = new JPanel();
            panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
            gbc.gridy = 1;
            gbc.weightx = 30;
            gbc.weighty = 30;
            gbc.insets = new Insets(2, 2, 2, 2);
            getContentPane().add(panel2, gbc);
            pack();
        }
    
        public static void main(String[] args) {
            new BorderPanels().setVisible(true);
        }
    }
    

提交回复
热议问题