How would I be able to achieve this expandable layout in Java? Flexible BoxLayout etc

前端 未结 2 753
梦谈多话
梦谈多话 2020-12-19 14:10

I would like to be able to have three JPanels p1 p2 and p3, and have them lay out like so:

\"Layout\"
I hav

相关标签:
2条回答
  • 2020-12-19 14:26

    not my favorite LayoutManager, example by using GridBagLayout, easiest could be to use MigLayout, maybe ...

    enter image description hereenter image description here

    enter image description here

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class BorderPanels extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        public BorderPanels() {
            setLayout(new GridBagLayout());// set LayoutManager
            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;
            add(panel1, gbc); // add compoenet to the COntentPane
    
            JPanel panel2 = new JPanel();
            panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
            gbc.gridy = 1;
            gbc.weightx = gbc.weighty = 30;
            gbc.insets = new Insets(2, 2, 2, 2);
            add(panel2, gbc); // add component to the COntentPane
    
            JPanel panel3 = new JPanel();
            panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
            gbc.gridx =1;
            gbc.gridy = 0;
            gbc.gridwidth = /*gbc.gridheight = */1;
            gbc.gridheight = 2;
            gbc.weightx = /*gbc.weighty = */20;
            gbc.insets = new Insets(2, 2, 2, 2);
            add(panel3, gbc);
    
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
            pack();
            setVisible(true); // important
        }
    
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
    
                public void run() {
                    BorderPanels borderPanels = new BorderPanels();
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-19 14:44

    One word: MigLayout. As you have seen, it is possible with the standard layout managers. But I can guarantee you, the layout code would be reduced to 4 lines with MigLayout... (Although it would take you some time to get into MigLayout as it works a bit different than the usual layout managers).

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