GridBagLayout是java裏面最重要的佈局管理器之一,可以做出很複雜的佈局,可以說GridBagLayout是必須要學好的的,
GridBagLayout
類是一個靈活的佈局管理器,它不要求組件的大小相同便可以將組件垂直、水平或沿它們的基線對齊。
每個 GridBagLayout
對象維持一個動態的矩形單元網格,每個組件佔用一個或多個這樣的單元,該單元被稱爲顯示區域。
下面就通過一個記事本案例去說明GridBagLayout的使用方法。
分析:
帶有箭頭的說明可以拉伸的。
4佔用4個格子,6佔用4個格子。如果設置6可以拉伸了,那麼4也會跟着拉伸。
但是如果設置4拉伸,那麼7所在的列也可以拉伸,所以4不能設置拉伸。我們應該設置4是跟隨6進行拉伸。
灰色的線是爲了看清佈局的大概,組件佔用的格子數。
package Layout;
import java.awt.*;
import javax.swing.*;
public class GridBagDemo extends JFrame {
JButton j1;
JButton j2;
JButton j3;
JPanel j4;
JComboBox j5;
JTextField j6;
JButton j7;
JList j8;
JTextArea j9;
public static void main(String args[]) {
GridBagDemo demo = new GridBagDemo();
}
public GridBagDemo() {
init();
this.setSize(600, 600);
this.setVisible(true);
}
public void init() {
j1 = new JButton("打開");
j2 = new JButton("保存");
j3 = new JButton("另存爲");
j4 = new JPanel();
String[] str = { "java筆記", "C#筆記", "HTML5筆記" };
j5 = new JComboBox(str);
j6 = new JTextField();
j7 = new JButton("清空");
j8 = new JList(str);
j9 = new JTextArea();
j9.setBackground(Color.PINK);// 爲了看出效果,設置了顏色
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
this.add(j1);// 把組件添加進jframe
this.add(j2);
this.add(j3);
this.add(j4);
this.add(j5);
this.add(j6);
this.add(j7);
this.add(j8);
this.add(j9);
GridBagConstraints s = new GridBagConstraints();// 定義一個GridBagConstraints,
// 是用來控制添加進的組件的顯示位置
s.fill = GridBagConstraints.BOTH;
// 該方法是爲了設置如果組件所在的區域比組件本身要大時的顯示情況
// NONE:不調整組件大小。
// HORIZONTAL:加寬組件,使它在水平方向上填滿其顯示區域,但是不改變高度。
// VERTICAL:加高組件,使它在垂直方向上填滿其顯示區域,但是不改變寬度。
// BOTH:使組件完全填滿其顯示區域。
s.gridwidth = 1;// 該方法是設置組件水平所佔用的格子數,如果爲0,就說明該組件是該行的最後一個
s.weightx = 0;// 該方法設置組件水平的拉伸幅度,如果爲0就說明不拉伸,不爲0就隨着窗口增大進行拉伸,0到1之間
s.weighty = 0;// 該方法設置組件垂直的拉伸幅度,如果爲0就說明不拉伸,不爲0就隨着窗口增大進行拉伸,0到1之間
layout.setConstraints(j1, s);// 設置組件
s.gridwidth = 1;
s.weightx = 0;
s.weighty = 0;
layout.setConstraints(j2, s);
s.gridwidth = 1;
s.weightx = 0;
s.weighty = 0;
layout.setConstraints(j3, s);
s.gridwidth = 0;// 該方法是設置組件水平所佔用的格子數,如果爲0,就說明該組件是該行的最後一個
s.weightx = 0;// 不能爲1,j4是佔了4個格,並且可以橫向拉伸,
// 但是如果爲1,後面行的列的格也會跟着拉伸,導致j7所在的列也可以拉伸
// 所以應該是跟着j6進行拉伸
s.weighty = 0;
layout.setConstraints(j4, s);
s.gridwidth = 2;
s.weightx = 0;
s.weighty = 0;
layout.setConstraints(j5, s);
;
s.gridwidth = 4;
s.weightx = 1;
s.weighty = 0;
layout.setConstraints(j6, s);
;
s.gridwidth = 0;
s.weightx = 0;
s.weighty = 0;
layout.setConstraints(j7, s);
;
s.gridwidth = 2;
s.weightx = 0;
s.weighty = 1;
layout.setConstraints(j8, s);
;
s.gridwidth = 5;
s.weightx = 0;
s.weighty = 1;
layout.setConstraints(j9, s);
}
}