package com.company; import javax.swing.*; import java.awt.*; public class Main extends JFrame { public Main(){ setBounds(100,100,300,300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c=getContentPane(); c.setLayout(new GridLayout(7,3,5,5));//设置为网格布局,7行3列,水平间距为5像素,垂直间距为5 for (int i=1;i<=20;i++){ c.add(new JButton("按钮"+i)); } setVisible(true); } public static void main(String[] args) { new Main(); // write your code here } }
当设定的水平垂直,间距不再适应时,网格布局会自动调整