Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

GridBaglayout -component size

843806Dec 11 2007 — edited Dec 14 2007
Here is my problem:

I want to layout 4 components, c1,..,c4 to a JPanel.
c1 and c3 should occupy 70 % in the horizontal direction and span 2 columns.
c2 and c4 should occupy 30 % in the horizontal direction, and span one column.
**** | ____col0 ___|__col1__|___col2_____|
Row0 |      c1 70%          |   c2 30%   |
Row1 | c3 30%      |    c4 70%           |
Whatever I tries all components occupies 50% along the horizontal axis.
What am I doing wrong?

Example code:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class GBTest extends JFrame{

    public GBTest(){
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        
        /* First row:*/
        panel.add(createPanel(Color.RED), createConstrains(0, 0, 2, 70));
        panel.add(createPanel(Color.GREEN), createConstrains(2, 0, 1, 30));
        
        /*Second row:*/
        panel.add(createPanel(Color.BLUE), createConstrains(0, 1, 1, 30));
        panel.add(createPanel(Color.YELLOW), createConstrains(1, 1, 2, 70));
        
        /* If we add this the above components gets the correct relative size: */
        //panel.add(createPanel(Color.BLACK), createConstrains(1,3,1,60));
        
        this.setContentPane(panel);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(400,400);
        this.setVisible(true);
    }
    
    public JPanel createPanel(Color bg){
        JPanel p = new JPanel();
        p.setBackground(bg);
        return p;
    }
    
    public GridBagConstraints createConstrains(int row, int col, int colspan, double xweight){
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = row;
        gc.gridy = col;
        gc.weightx = xweight;
        gc.gridwidth = colspan;
        gc.fill = GridBagConstraints.BOTH;
        gc.weighty = 10;
        return gc;
    }
    
    public static void main(String[] args){
        new GBTest();
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 11 2008
Added on Dec 11 2007
3 comments
152 views