布局管理器的可视指南

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

几个 AWT 和 Swing 类提供了一般用途的布局管理器:

本节显示使用这些布局管理器的示例 GUI,并告诉您在何处查找每个布局管理器的操作方法页面。您可以在操作方法页面和示例索引中找到用于运行示例的链接。


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 中使用布局。

BorderLayout 的

A picture of a GUI that uses BorderLayout

每个内容窗格都初始化为使用BorderLayout。 (正如使用顶级容器所解释的那样,内容窗格是所有框架,小程序和对话框中的主要容器。)BorderLayout将组件放置在最多五个区域:顶部,底部,左侧,对,中心。所有额外空间均位于中心区域。如果您希望能够将杆拖离其起始位置,则必须在BorderLayout容器内创建使用 JToolBar 创建的工具栏。有关详细信息,请参阅如何使用 BorderLayout

A picture of a GUI that uses BoxLayout

BoxLayout类将组件放在单个行或列中。它尊重组件所要求的最大尺寸,并允许您对齐组件。有关详细信息,请参阅如何使用 BoxLayout

A picture of a GUI that uses CardLayout Another picture of the same layout

CardLayout类允许您在不同时间实现包含不同组件的区域。 CardLayout通常由组合框控制,组合框的状态决定CardLayout显示哪个面板(组件组)。使用CardLayout的另一种方法是使用选项卡式窗格,它提供类似的功能,但具有预定义的 GUI。有关详细信息,请参阅如何使用 CardLayout

A picture of a GUI that uses FlowLayout

FlowLayout是每个JPanel的默认布局管理器。它只是将组件放在一行中,如果它的容器不够宽,则开始一个新行。 CardLayoutDemo 中的两个面板(以前显示为 )都使用FlowLayout。有关详细信息,请参阅如何使用 FlowLayout

A picture of a GUI that uses GridBagLayout

GridBagLayout是一个复杂,灵活的布局管理器。它通过将组件放置在单元格网格中来对齐组件,从而允许组件跨越多个单元格。网格中的行可以具有不同的高度,并且网格列可以具有不同的宽度。有关详细信息,请参阅如何使用 GridBagLayout

A picture of a GUI that uses GridLayout

GridLayout只是使一组组件大小相等,并以请求的行数和列数显示它们。有关详细信息,请参阅如何使用 GridLayout

A picture of a GUI that uses GroupLayout

GroupLayout是为 GUI 构建器工具开发的布局管理器,但也可以手动使用。 GroupLayout分别与水平和垂直布局配合使用。为每个维度单独定义布局。因此,每个组件需要在布局中定义两次。上面显示的查找窗口是GroupLayout的示例。有关详细信息,请参阅如何使用 GroupLayout

A picture of a GUI that uses SpringLayout

Another GUI that uses SpringLayout

SpringLayout是一个灵活的布局管理器,专为 GUI 构建器使用而设计。它允许您指定其控制下的组件边缘之间的精确关系。例如,您可以定义一个组件的左边缘是从第二个组件的右边缘开始的某个距离(可以动态计算)。 SpringLayout根据一组约束条件列出其相关容器的子项,如如何使用 SpringLayout 中所示。