GridLayout怎么用
时间: 2023-07-06 16:44:06 浏览: 38
GridLayout是一种将容器划分为行和列的布局管理器,每个单元格中可以添加一个组件。下面是一个简单的示例,演示如何使用GridLayout布局管理器:
```java
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class GridLayoutExample {
public static void main(String[] args) {
// 创建一个JFrame窗口
JFrame frame = new JFrame("GridLayout Example");
// 创建一个JPanel面板
JPanel panel = new JPanel();
// 设置面板的布局管理器为GridLayout,指定为3行3列的网格布局
panel.setLayout(new GridLayout(3, 3));
// 循环添加9个按钮
for (int i = 1; i <= 9; i++) {
JButton button = new JButton("Button" + i);
panel.add(button);
}
// 将面板添加到窗口中
frame.add(panel);
// 设置窗口的大小、位置和关闭方式
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 显示窗口
frame.setVisible(true);
}
}
```
上面的示例中,创建了一个3行3列的网格布局,循环添加了9个按钮,然后将面板添加到窗口中。运行程序,就可以看到9个按钮按照3行3列的方式排列在窗口中。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)