標籤:
GridBagLayout以表格形式布置容器內的組件,將每個組件放置在每個單元格內,而一個單元格可以跨越多個單元格合并成一個單元格,即多個單元格可以組合成一個單元格,從而實現組件的自由布局。
GridBagLayout是一個靈活的布局管理器,組件如果想加入其中需藉助GridBagConstraints,其中有若干個參數
1.構造方法
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。
2.執行個體
<span style="font-family:SimHei;font-size:18px;"> import java.awt.*; import java.util.*; import java.applet.Applet; public class GridBagEx1 extends Applet { protected void makebutton(String name, GridBagLayout gridbag, GridBagConstraints c) { Button button = new Button(name); gridbag.setConstraints(button, c); add(button); } public void init() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setFont(new Font("SansSerif", Font.PLAIN, 14)); setLayout(gridbag); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; makebutton("Button1", gridbag, c); makebutton("Button2", gridbag, c); makebutton("Button3", gridbag, c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makebutton("Button4", gridbag, c); c.weightx = 0.0; //reset to the default makebutton("Button5", gridbag, c); //another row c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row makebutton("Button6", gridbag, c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makebutton("Button7", gridbag, c); c.gridwidth = 1; //reset to the default c.gridheight = 2; c.weighty = 1.0; makebutton("Button8", gridbag, c); c.weighty = 0.0; //reset to the default c.gridwidth = GridBagConstraints.REMAINDER; //end row c.gridheight = 1; //reset to the default makebutton("Button9", gridbag, c); makebutton("Button10", gridbag, c); setSize(300, 100); } public static void main(String args[]) { Frame f = new Frame("GridBagLayout執行個體"); GridBagEx1 ex1 = new GridBagEx1(); ex1.init(); f.add("Center", ex1); f.pack(); f.setSize(f.getPreferredSize()); f.setVisible(true); } } </span>
3.結果
java Swing布局管理之GridBagLayout布局