GridBagLayout : weighty and weightx

weightx : To specify the horizontal stretch of the component to fill the display area of the container. The default value is 0.

weighty : To specify the vertical stretch of the component to fill the display area of the container. The default value is 0.

Program

tdrt

 

Program Source

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

class GridBagLayt extends JFrame {
 
    GridBagLayt()
    {
        setTitle("GridBagLayout");
        GridBagLayout lay = new GridBagLayout();
        GridBagConstraints cons = new GridBagConstraints();
        setLayout(lay);
        setweightxAndweighty(cons,1,1);
        setButton("button1",0,0,cons,lay);
        setButton("button2",0,1,cons,lay);
        setButton("button3",0,2,cons,lay);
        setButton("button4",1,0,cons,lay);
        setButton("button5",1,1,cons,lay);
        setButton("button6",1,2,cons,lay);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(700,200);
        setVisible(true);

    }
 
    void setButton(String name,int y,int x,GridBagConstraints gbc,GridBagLayout lay)
    {
        JButton jb = new JButton(name);
        gbc.gridy = y;
        gbc.gridx = x;
        lay.setConstraints(jb, gbc);
        add(jb);
    }
 
    void setweightxAndweighty(GridBagConstraints gbc,int weighty,int weightx)
    {
        gbc.weighty = weighty;
        gbc.weightx = weightx;
    }
}

public class Javaapp {
 
    public static void main(String[] args) {
     
        GridBagLayt gb = new GridBagLayt();
    }
}

Leave a Comment