GridBagLayout是java裏面最重要的佈局管理器之一,可以做出很複雜的佈局,可以說GridBagLayout是必須要學好的的,
GridBagLayout
類是一個靈活的佈局管理器,它不要求組件的大小相同便可以將組件垂直、水平或沿它們的基線對齊。
每個 GridBagLayout
對象維持一個動態的矩形單元網格,每個組件佔用一個或多個這樣的單元,該單元被稱爲顯示區域。
下面就通過一個記事本案例去說明GridBagLayout的使用方法。
分析:
帶有箭頭的說明可以拉伸的。
4佔用4個格子,6佔用4個格子。如果設置6可以拉伸了,那麼4也會跟着拉伸。
但是如果設置4拉伸,那麼7所在的列也可以拉伸,所以4不能設置拉伸。我們應該設置4是跟隨6進行拉伸。
灰色的線是爲了看清佈局的大概,組件佔用的格子數。
運行時的顯示效果
代碼如下:
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo 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) {
GridBagLayoutDemo demo = new GridBagLayoutDemo();
}
public GridBagLayoutDemo(){
init();
this.setSize(600,600);
this.setVisible(true);
}
/**
*
*/
private 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.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();
s.fill = GridBagConstraints.BOTH;
s.gridwidth = 1;
s.weightx =0;
s.weighty =0;
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;
s.weightx=0;
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=0.2;
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);
this.setLayout(layout);
}
}
原文鏈接:https://www.cnblogs.com/taoweiji/archive/2012/12/14/2818787.html