import javax.swing.*;
import java.awt.*;
/**
* @author 许泽鑫
* @data 2019/11/8 - 20:00
*/
public class Demo8 extends JFrame {
public Demo8(){
setSize(800,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new GridBagLayout());
setVisible(true);
GridBagConstraints g = new GridBagConstraints();
g.gridx = 1;//设置在网格组中的坐标位置
g.gridy = 1;
g.ipadx = 10;
g.ipady = 10;
// g.fill = GridBagConstraints.NONE;//不填充 居中;
// g.anchor = GridBagConstraints.NORTH;
c.add(new JButton("组件"),g);
GridBagConstraints g1 = new GridBagConstraints();
g1.gridx = 3;
g1.gridy = 1;
g1.gridwidth =2; //设置在网格中占的大小 这里表示该组件的宽占两个网格
g1.gridheight = 1;
g1.anchor = GridBagConstraints.NORTH;
g1.fill = GridBagConstraints.HORIZONTAL;//水平填充
c.add(new JButton("组件2"),g1);
JPanel p =new JPanel();
g1.gridx = 3;
g1.gridy = 1;
g1.gridwidth =2; //设置在网格中占的大小 这里表示该组件的宽占两个网格
g1.gridheight = 2;
g1.fill = GridBagConstraints.BOTH;
p.setBackground(Color.green);
c.add(p,g1);
GridBagConstraints g4 = new GridBagConstraints();
g4.gridx =5;
g4.gridy = 1;
g4.gridwidth = 2; //
g4.gridheight = 2;
g4.fill = GridBagConstraints.VERTICAL;//垂直填充
c.add(new JButton("组件3"),g4);
GridBagConstraints g5 = new GridBagConstraints();
g5.gridx =7;
g5.gridy = 1;
g5.gridwidth = 2; //
g5.gridheight = 2;
g5.fill = GridBagConstraints.BOTH;//全部填充
c.add(new JButton("组件4"),g5);
for(int i = 0; i<9;i++){
GridBagConstraints g2 = new GridBagConstraints();
g2.gridx = i;
g2.gridy = 0;
c.add(new JButton("组件"),g2);
GridBagConstraints g3 = new GridBagConstraints();
g3.gridy = i;
g3.gridx = 0;
c.add(new JButton("组件"),g3);
}
}
public static void main(String[] args) {
new Demo8();
}
}
网格组布局
最新推荐文章于 2021-08-13 17:39:48 发布