[url=http://www.51zxw.net/study.asp?vip=8963801] 学IT必看,【经典】 【基础】 【进阶】 【实践 】 【成神】【超神】【返璞归真】
[/url]
package layoutDemos;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridBagLayoutDemo extends JFrame {
public GridBagLayoutDemo() {
this.setSize(500, 500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
InitControl();
}
JPanel jTop, Jbuttom, jLeft, jright, jbuttom1, pFull;
private void InitControl() {
jTop = new JPanel();
jTop.setBackground(Color.red);
jLeft = new JPanel();
jLeft.setBackground(Color.yellow);
jright = new JPanel();
jright.setBackground(Color.green);
jbuttom1 = new JPanel();
jbuttom1.setBackground(Color.gray);
Jbuttom = new JPanel();
Jbuttom.setBackground(Color.blue);
pFull = new JPanel();
pFull.setBackground(Color.magenta);
pFull.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1; // 从第几列开始相当于x坐标
gbc.gridy = 0; // 从第几行开始相当于y坐标
gbc.weightx =0; //大于0表示宽度根据窗体的大小改变而改变,等于0表示不变
gbc.weighty = 0; //大于0表示高度跟句窗体的大小改变而改变,等于0表示不变
gbc.gridwidth = 2; //占据列数
gbc.gridheight = 1; //占据行数
gbc.ipadx=400; //宽度 weightx=0有效 大于0无效 ; 宽高度有没有效果跟 fill的值也有关系
gbc.ipady=100; //高度 weighty=0有效 大于0无效 ; 度高度有没有效果跟 fill的值也有关系
gbc.fill= GridBagConstraints.BOTH;
pFull.add(jTop, gbc);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 1; // 列
gbc1.gridy = 1; // 行
gbc1.weightx = 0;
gbc1.weighty =0;
gbc1.gridwidth = 1;
gbc1.gridheight = 1;
gbc1.fill= GridBagConstraints.BOTH;
pFull.add(jLeft, gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 2; // 列
gbc2.gridy = 1; // 行
gbc2.weightx = 1.0;
gbc2.weighty = 1.0;
gbc2.gridwidth = 1;
gbc2.gridheight = 1;
gbc2.fill= GridBagConstraints.BOTH;
pFull.add(jright, gbc2);
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 1; // 列
gbc3.gridy = 3; // 行
gbc3.weightx = 100;
gbc3.weighty = 0;
gbc3.gridwidth = 2;
gbc3.gridheight = 1;
gbc3.ipadx=200;
gbc3.ipady =100;
gbc3.fill= GridBagConstraints.BOTH;
pFull.add(jbuttom1, gbc3);
GridBagConstraints gbc4 = new GridBagConstraints();
gbc4.gridx = 1; // 列
gbc4.gridy = 4; // 行
gbc4.weightx = 0;
gbc4.weighty = 0;
gbc4.gridwidth = 2;
gbc4.gridheight = 1;
gbc4.ipadx=100;
gbc4.ipady=20;
gbc4.fill= GridBagConstraints.BOTH;
pFull.add(Jbuttom, gbc4);
this.add(pFull);
}
public static void main(String[] args) {
GridBagLayoutDemo gDemo = new GridBagLayoutDemo();
gDemo.setVisible(true);
}
}