本示例使用GridLayout来创建四乘四网格布局。我们在每个网格中放置一个JTextField组件来读取用户输入。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; public class GridLayoutDemo extends JFrame { public GridLayoutDemo() { initializeUI(); } private void initializeUI() { setSize(300,300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // 创建水平和垂直5像素的四乘四GridLayout // 每行或每列之间的间隙。 GridLayout grid = new GridLayout(4, 4, 5, 5); //grid.setColumns(4); //grid.setRows(4); //grid.setHgap(5); //grid.setVgap(5); setLayout(grid); JTextField[][] textFields = new JTextField[4][4]; for (int i = 0; i < textFields.length; i++) { for (int j = 0; j < textFields[i].length; j++) { textFields[i][j] = new JTextField(String.valueOf((i + 1) * (j + 1))); // 将文本放在JTextField组件的中心 textFields[i][j].setHorizontalAlignment(SwingConstants.CENTER); getContentPane().add(textFields[i][j]); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new GridLayoutDemo().setVisible(true); } }); } }