網格袋佈局類似於Win8的Metro佈局,用於將組件按大小比例放在不同位置的網格內,各組件的實際大小會隨着窗口的改變而改變,但相對位置不變,能夠很好的適應屏幕。
通過閱讀《21天學通Java》這本書,發現了一個佈局組件的很好的例子,遂摘錄下來,供分享和複習。
在這本書中,舉了一個郵件窗口的例子,需要的佈局規劃如下:
其中,二維座標表示網格相對位置,以(0,0)爲網格的起點,橫x豎y,後面的width指的是橫向跨越的單元格數。注意,網格是由一個或多個單元格組成的整體。
常用屬性有;
gridx gridy: 單元格位置,如果跨越多個格則爲左上角位置
gridwidth gridheight: 組件水平、垂直方向跨越的格數
weightx weighty: 組件相對於同一行、列內其他組件的大小(相對權重)
fill: 水平或者垂直方向拉伸,可選屬性如下(實質int)
GridBagConstraints內的常成員:NONE HORIZONTAL VERITAL BOTH
anchor: 對齊方式,可選屬性如下(實質int)
GridBagConstraints內的常成員:WEST EAST 分別爲向左、右單元格對齊
爲了能夠簡化代碼,可以製作一個佈局方法,每次只需要調用方法遍完成一個組件的佈局。示例代碼如下:
import java.awt.*; import javax.swing.*; public class learn3 extends JFrame{ GridBagLayout gridbag = new GridBagLayout(); public learn3(){ super("Message"); setSize(380,120); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLookAndFeel(); setLayout(gridbag); JLabel toLabel = new JLabel("To:"); JTextField to = new JTextField(); JLabel subjectLabel = new JLabel("subject:"); JTextField subject = new JTextField(); JLabel ccLabel = new JLabel("CC:"); JTextField cc = new JTextField(); JLabel bccLabel = new JLabel("Bcc"); JTextField bcc = new JTextField(); addComponent(toLabel,0,0,1,1,10,100,GridBagConstraints.NONE, GridBagConstraints.EAST); addComponent(to,1,0,9,1,90,100,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST); addComponent(subjectLabel,0,1,1,1,10,100,GridBagConstraints.NONE, GridBagConstraints.EAST); addComponent(subject,1,1,9,1,90,100,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST); addComponent(ccLabel,0,2,1,1,10,100,GridBagConstraints.NONE, GridBagConstraints.EAST); addComponent(cc,1,2,4,1,40,100,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST); addComponent(bccLabel,5,2,1,1,10,100,GridBagConstraints.NONE, GridBagConstraints.EAST); addComponent(bcc,6,2,4,1,40,100,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST); setVisible(true); } private void addComponent(Component comp,int gridx,int gridy ,int gridwidth, int gridheight, int weightx, int weighty, int fill, int anchor) { GridBagConstraints constraint = new GridBagConstraints(); constraint.gridx = gridx; constraint.gridy = gridy; constraint.gridwidth = gridwidth; constraint.gridheight = gridheight; constraint.weightx = weightx; constraint.weighty = weighty; constraint.fill = fill; constraint.anchor = anchor; gridbag.setConstraints(comp, constraint); add(comp); } private void setLookAndFeel(){ try{ UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this); } catch(Exception exc){ //ignore error } } public static void main(String[] args) { learn3 learn = new learn3(); } }