首页 > 代码库 > 使用GridBagLayout控制行列的高度和宽度
使用GridBagLayout控制行列的高度和宽度
摘自http://bbs.csdn.net/topics/340189065
使用GridBagLayout控制行列的高度和宽度
gridwidth指定组件显示区域的某一行中的单元格数。 默认值1,水平占一格
gridheight指定在组件显示区域的一列中的单元格数。默认值1,垂直占一格
weightx指定如何分布额外的水平空间。 默认值0,额外水平空间不分配。
weighty指定如何分布额外的垂直空间。 默认值0,额外垂直空间不分配。
拉伸后效果如下
1 package com.hw.gridbaglayout; 2 3 import java.awt.Button; 4 import java.awt.Font; 5 import java.awt.GridBagConstraints; 6 import java.awt.GridBagLayout; 7 import java.awt.event.WindowAdapter; 8 import java.awt.event.WindowEvent; 9 10 import javax.swing.JFrame; 11 import javax.swing.JPanel; 12 13 public class GridBagEx2 extends JPanel 14 { 15 private static final long serialVersionUID = -5214441555967215113L; 16 17 protected void makebutton(String name, GridBagLayout gridbag, 18 GridBagConstraints c) 19 { 20 Button button = new Button(name); 21 gridbag.setConstraints(button, c); 22 add(button); 23 } 24 25 public void init() 26 { 27 GridBagLayout gridbag = new GridBagLayout(); 28 GridBagConstraints c = new GridBagConstraints(); 29 30 setFont(new Font("SansSerif", Font.PLAIN, 14)); 31 setLayout(gridbag); 32 33 c.fill = GridBagConstraints.BOTH; 34 c.weightx = 1.0; 35 makebutton("Button1", gridbag, c); 36 makebutton("Button2", gridbag, c); 37 makebutton("Button3", gridbag, c); 38 39 c.gridwidth = GridBagConstraints.REMAINDER; //end row 40 makebutton("Button4", gridbag, c); 41 42 c.weightx = 0.0; //reset to the default 43 makebutton("Button5", gridbag, c); //another row 44 45 c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row 46 makebutton("Button6", gridbag, c); 47 48 c.gridwidth = GridBagConstraints.REMAINDER; //end row 49 makebutton("Button7", gridbag, c); 50 51 c.gridwidth = 1; //reset to the default 52 c.gridheight = 2; 53 c.weighty = 1.0; 54 makebutton("Button8", gridbag, c); 55 56 c.weighty = 0.0; //reset to the default 57 c.gridwidth = GridBagConstraints.REMAINDER; //end row 58 c.gridheight = 1; //reset to the default 59 makebutton("Button9", gridbag, c); 60 makebutton("Button10", gridbag, c); 61 62 setSize(300, 100); 63 } 64 65 public static void main(String args[]) 66 { 67 JFrame f = new JFrame("GridBag Layout Example"); 68 f.setLocation(400, 200); 69 GridBagEx2 ex1 = new GridBagEx2(); 70 71 ex1.init(); 72 73 f.add("Center", ex1); 74 f.pack(); 75 f.setSize(f.getPreferredSize()); 76 f.setVisible(true); 77 f.addWindowListener(new WindowAdapter() 78 { 79 80 @Override 81 public void windowClosing(WindowEvent e) 82 { 83 System.exit(0); 84 } 85 86 }); 87 } 88 89 }
使用GridBagLayout控制行列的高度和宽度
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。