2, JavaSwing layout manager-GridLayout (grid layout)

Overview

Official JavaDocsApi: https://docs.oracle.com/javase/8/docs/api/java/awt/GridLayout.html

 

GridLayout, grid layout manager. It arranges the components of the container in the form of a rectangular grid, divides the container into rectangular grids of equal size according to rows and columns, and places a component in a grid, and the width and height of the components automatically fill the grid.

 

Give priority to the number of rows and total number: When both the number of rows and columns are set to non-zero values ​​through the construction method or the setRows and setColumns methods, the specified number of columns will be ignored. The number of columns is determined by the number of rows specified and the total number of components in the layout. So, for example, if three rows and two columns are specified, and nine components are added to the layout, they will appear as three rows and three columns. Only when the number of rows is set to zero, the specified number of columns is valid for the layout.

 

GridLayout construction method:

GridLayout()

 

Default structure, each component occupies one row and one column

GridLayout(int rows, int cols)

 

Grid layout with specified number of rows and columns

GridLayout(int rows, int cols, int hgap, int vgap)

 

Specify the grid layout of the number of rows and columns, and specify the horizontal and vertical grid gaps

Code case

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * 测试网格布局
 * @author 28250
 *
 */

public class TestGridTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame jf = new JFrame();
		jf.setSize(400,300);  //大小
		jf.setTitle("网格布局");  //设置标题 
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭并退出
		jf.setLocationRelativeTo(null);  //居中
		
		//创建3*3的网格布局
		GridLayout layout = new GridLayout(3,3);
		//设置间隙
		layout.setHgap(10);  //水平间隙
		layout.setVgap(10);  //竖直间隙
		
		//创建中间容器 并设置布局
		JPanel panel = new JPanel(layout);
		
		JButton btn1 = new JButton("按钮1");
		JButton btn2 = new JButton("按钮2");
		JButton btn3 = new JButton("按钮3");
		JButton btn4 = new JButton("按钮4");
		JButton btn5 = new JButton("按钮5");
		JButton btn6 = new JButton("按钮6");
		JButton btn7 = new JButton("按钮7");
		JButton btn8 = new JButton("按钮8");
		
		panel.add(btn1);
		panel.add(btn2);
		panel.add(btn3);
		panel.add(btn4);
		panel.add(btn5);
		panel.add(btn6);
		panel.add(btn7);
		panel.add(btn8);
		
		//将中间容器添加到窗口中
		jf.setContentPane(panel);
		
		jf.setVisible(true);
	}

}

Guess you like

Origin blog.csdn.net/qq_43629083/article/details/109017518