如何使用 GridLayout

原文: https://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html


Note: This lesson covers writing layout code by hand, which can be challenging. If you are not interested in learning all the details of layout management, you might prefer to use the GroupLayout layout manager combined with a builder tool to lay out your GUI. One such builder tool is the NetBeans IDE. Otherwise, if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager.


如果您对使用 JavaFX 创建 GUI 感兴趣,请参阅在 JavaFX 中使用布局。

下图表示使用 GridLayout 类的应用程序的快照。

A snapshot of GridLayoutDemo

单击“启动”按钮以使用 Java™Web Start下载 JDK 7 或更高版本)运行 GridLayoutDemo。或者,要自己编译并运行示例,请参考示例索引

Launches the GridLayoutDemo application

该演示的完整代码位于 GridLayoutDemo.java 文件中。

GridLayout对象将组件放置在单元格网格中。每个组件占用其单元中的所有可用空间,并且每个单元的大小完全相同。如果GridLayoutDemo窗口调整大小,GridLayout对象会更改单元格大小,以便在给定容器可用空间的情况下,单元格尽可能大。

下面的代码片段创建GridLayout对象及其管理的组件。

  1. GridLayout experimentLayout = new GridLayout(0,2);
  2. ...
  3. compsToExperiment.setLayout(experimentLayout);
  4. compsToExperiment.add(new JButton("Button 1"));
  5. compsToExperiment.add(new JButton("Button 2"));
  6. compsToExperiment.add(new JButton("Button 3"));
  7. compsToExperiment.add(new JButton("Long-Named Button 4"));
  8. compsToExperiment.add(new JButton("5"));

GridLayout类的构造器根据需要创建一个具有两列和多行的实例。

使用组合框设置在组件周围放置多少垂直或水平填充。然后单击“应用间隙”按钮。以下代码段显示了如何使用GridLayout类的setVgapsetHgap方法处理选择:

  1. applyButton.addActionListener(new ActionListener(){
  2. public void actionPerformed(ActionEvent e){
  3. //Get the horizontal gap value
  4. String horGap = (String)horGapComboBox.getSelectedItem();
  5. //Get the vertical gap value
  6. String verGap = (String)verGapComboBox.getSelectedItem();
  7. //Set up the horizontal gap value
  8. experimentLayout.setHgap(Integer.parseInt(horGap));
  9. //Set up the vertical gap value
  10. experimentLayout.setVgap(Integer.parseInt(verGap));
  11. //Set up the layout of the buttons
  12. experimentLayout.layoutContainer(compsToExperiment);
  13. }
  14. });

下表列出了GridLayout类的构造器,它指定了行数和列数。

The GridLayout class constructors | 构造器 | 目的 | | —- | —- | | GridLayout(int _ 行*,int _cols_ ) | 创建具有指定行数和列数的网格布局。布局中的所有组件都具有相同的大小。 rowscols中的一个(但不是两个)可以为零,这意味着可以将任意数量的对象放置在行中或列中。 | | GridLayout(int _ 行*,int _cols_ ,int _hgap_ ,int _vgap_ ) | 创建具有指定行数和列数的网格布局。此外,水平和垂直间隙设置为指定值。水平间隙是每列之间的位置。在每行之间放置垂直间隙。 |

GridLayout类有两个构造器:

的示例

下表列出了使用GridLayout类并提供相关部分链接的代码示例。

在哪里描述 笔记
GridLayoutDemo 这一页 使用 2 列网格。
ComboBoxDemo2 如何使用组合框 使用 1x1 网格使组件尽可能大的许多示例之一。
LabelDemo 如何使用标签 使用 3 行网格。