今天終于耐著性子弄懂了GridBagLayout是怎么使用的。
構造函數:
GirdBagLayout()建立一個新的GridBagLayout管理器。
GridBagConstraints()建立一個新的GridBagConstraints對象。
GridBagConstraints(int gridx,int gridy,
int gridwidth,int gridheight,
double weightx,double weighty,
int anchor,int fill, Insets insets,
int ipadx,int ipady)建立一個新的GridBagConstraints對象,并指定其參數的值。
看著這一堆的參數就快煩死了,下面就了解一下參數的意思:
參數說明:
gridx,gridy —— 設置組件的位置,
gridx設置為GridBagConstraints.RELATIVE代表此組件位于之前所加入組件的右邊。
gridy設置為GridBagConstraints.RELATIVE代表此組件位于以前所加入組件的下面。
建議定義出gridx,gridy的位置以便以后維護程序。gridx=0,gridy=0時放在0行0列。
gridwidth,gridheight —— 用來設置組件所占的單位長度與高度,默認值皆為1。
你可以使用GridBagConstraints.REMAINDER常量,代表此組件為此行或此列的最后一個組件,而且會占據所有剩余的空間。
weightx,weighty —— 用來設置窗口變大時,各組件跟著變大的比例。
當數字越大,表示組件能得到更多的空間,默認值皆為0。
anchor —— 當組件空間大于組件本身時,要將組件置于何處。
有CENTER(默認值)、NORTH、NORTHEAST、EAST、SOUTHEAST、WEST、NORTHWEST選擇。
insets —— 設置組件之間彼此的間距。
它有四個參數,分別是上,左,下,右,默認為(0,0,0,0)。
ipadx,ipady —— 設置組件間距,默認值為0。
GridBagLayout里的各種設置都必須通過GridBagConstraints,因此當我們將GridBagConstraints的參數都設置
好了之后,必須new一個GridBagConstraints的對象出來,以便GridBagLayout使用。
代碼片斷:
JButton b;
GridBagConstraints c;
int gridx,gridy,gridwidth,gridheight,anchor,fill,ipadx,ipady;
double weightx,weighty;
Insets inset;
JFrame f=new JFrame();
GridBagLayout gridbag=new GridBagLayout();
Container contentPane=f.getContentPane();
contentPane.setLayout(gridbag);
b=new JButton("first");
gridx=0;
gridy=0;
gridwidth=1;
gridheight=1;
weightx=10;
weighty=1;
anchor=GridBagConstraints.CENTER;
fill=GridBagConstraints.HORIZONTAL;
inset=new Insets(0,0,0,0);
ipadx=0;
ipady=0;
c=new GridBagConstraints(gridx,gridy,gridwidth,gridheight,weightx,weighty,anchor,fill,inset,ipadx,ipady);
gridbag.setConstraints(b,c);
contentPane.add(b);
GridBagLayout這種管理器是十分靈活的,只不過他寫起來比較麻煩,不過用了之后才發現他對界面的部署幫助很大。
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/dracularking/archive/2008/04/22/2314336.aspx