testgridbaglayout.java

来自「java实例之GridBagLayout布局管理器」· Java 代码 · 共 61 行

JAVA
61
字号
// GridBagLayout布局管理器示例
import java.awt.*;
import java.util.*;

 public class TestGridBagLayout {
 Frame f;     
 protected void makebutton(String name,GridBagLayout gridbag, GridBagConstraints c) {
         Button button = new Button(name);
         gridbag.setConstraints(button, c);
         f.add(button);
     }

     public void create() {
    	 f = new Frame("GridBagLayout Example");
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();

         f.setFont(new Font("simsun", Font.PLAIN, 14));
         f.setLayout(gridbag);

         c.fill = GridBagConstraints.BOTH;//按水平、垂直填充组件的显示区
         c.weightx = 1.0;
         makebutton("按钮1", gridbag, c);
         makebutton("按钮2", gridbag, c);
         c.gridwidth = GridBagConstraints.REMAINDER;   //是当前行的最后一个组件     
         makebutton("按钮3", gridbag, c);
         
         c.insets=new Insets(-10,-10,-10,-10);  //设置空白区,当为负数时,将跨越其显示区范围
         c.fill = GridBagConstraints.BOTH;   //按组件的最佳尺寸填充
         c.gridwidth = 2;                    //组件显示区行的大小
         c.weightx = 0.0;		          //组件的显示区可占用的额外空间大小
         makebutton("按钮4", gridbag, c); 
         c.insets=new Insets(0,0,0,0);     //设置空白显示区
 	     c.gridwidth=GridBagConstraints.RELATIVE; //当前行最后一个组件的下一个
         makebutton("按钮5", gridbag, c);
         c.gridwidth = GridBagConstraints.REMAINDER;
         makebutton("按钮6", gridbag, c);

        c.gridwidth = 1;	 //组件显示区行的大小   	   
 	    c.gridheight = 1;    //组件显示区列的大小
        c.weighty = 1.0;
        c.anchor=GridBagConstraints.CENTER;   //组件在显示区的中心
        makebutton("按钮7", gridbag, c);

        c.weighty = 0.0;		   
 	    c.gridwidth = GridBagConstraints.REMAINDER; 
 	    c.gridheight = 2;		  
        makebutton("按钮8", gridbag, c);
        makebutton("按钮9", gridbag, c);

         f.setSize(500, 300);
         f.setVisible(true);
     }

     public static void main(String args[]) {
 	   TestGridBagLayout ex1 = new TestGridBagLayout();
 	   ex1.create();
	  
     }
 }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?