How to use GridBagConstraints to create the layout?

后端 未结 3 1097
傲寒
傲寒 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:25

    In general, for gridbag layout

    • if you want a component scale, you must give its scale direction a weight, and any sizes (width/height) you set for that direction will be ignored by the layout manager.

    • If you don't want a component scale, the component must have its size defined (if you want, you can dig into this topic in documents of java). In your case of the bottom panel, you need to give its, at least, a preferred height.

    This can work as your expectation

    pnlTop.setBackground(Color.WHITE);
    pnlBottom.setBackground(Color.BLUE);
    
    // Because you don't want the bottom panel scale, you need to give it a height.
    // Because you want the bottom panel scale x, you can give it any width as the
    // layout manager will ignore it.
    pnlBottom.setPreferredSize(new Dimension(1, 20));
    
    
    getContentPane().setLayout(new GridBagLayout());
    GridBagConstraints cst = new GridBagConstraints();
    cst.fill = GridBagConstraints.BOTH;
    cst.gridx = 0;
    cst.gridy = 0;
    cst.weightx = 1.0; // --> You miss this for the top panel
    cst.weighty = 1.0;
    getContentPane().add(pnlTop, cst);
    
    cst = new GridBagConstraints();
    cst.fill = GridBagConstraints.HORIZONTAL;
    cst.gridx = 0;
    cst.gridy = 1;
    cst.weightx = 1.0; // You miss this for the bottom panel
    cst.weighty = 0.0;
    getContentPane().add(pnlBottom, cst);
    

    Further more, if you want to use gridbag layout, I recommend you to try the painless-gridbag library http://code.google.com/p/painless-gridbag/ (I'm the author of that library). It doesn't solve this problem for you (as your problem concerns managing component's size in gridbag layout) but it will save you a lot of typing and make your code easier to maintain

    pnlBottom.setPreferredSize(new Dimension(1, 20));
    
    PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);
    gbl.row().cell(pnlTop).fillXY();
    gbl.row().cell(pnlBottom).fillX();
    gbl.done();
    

提交回复
热议问题