Java BoxLayout

17 Mar 2025 | 5 分钟阅读

Java BoxLayout 类 用于垂直或水平排列组件。为此,BoxLayout 类提供了四个常量。它们如下所示

注意:BoxLayout 类位于 javax.swing 包中。

BoxLayout 类的字段

  1. public static final int X_AXIS: 组件的对齐方式从左到右水平排列。
  2. public static final int Y_AXIS: 组件的对齐方式从上到下垂直排列。
  3. public static final int LINE_AXIS: 组件的对齐方式类似于文本行中单词的排列方式,这取决于容器的 ComponentOrientation 属性。如果容器的 ComponentOrientation 属性是水平的,则组件水平对齐;否则,组件垂直对齐。对于水平方向,我们有两种情况:从左到右和从右到左。如果容器的 ComponentOrientation 属性值是从左到右,则组件从左到右渲染,而对于从右到左,组件也从右到左渲染。在垂直方向上,组件始终从上到下渲染。
  4. public static final int PAGE_AXIS: 组件的对齐方式类似于文本行在页面上的放置方式,这取决于容器的 ComponentOrientation 属性。如果容器的 ComponentOrientation 属性是水平的,则组件垂直对齐;否则,组件水平对齐。对于水平方向,我们有两种情况:从左到右和从右到左。如果容器的 ComponentOrientation 属性值也是从左到右,则组件从左到右渲染,而对于从右到左,组件的渲染是从右到左。在垂直方向上,组件始终从上到下渲染。

BoxLayout 类的构造函数

  1. BoxLayout(Container c, int axis): 创建一个 box layout,它使用给定的轴排列组件。

带有 Y 轴的 BoxLayout 类的示例

文件名: BoxLayoutExample1.java

输出

BoxLayout class example

带有 X 轴的 BoxLayout 类的示例

文件名: BoxLayoutExample2.java

输出

BoxLayout class example

带有 LINE_AXIS 的 BoxLayout 类的示例

以下示例显示了将容器的 ComponentOrientation 属性设置为 RIGHT_TO_LEFT 的效果。如果我们不设置 ComponentOrientation 属性的值,则组件将从左到右布局。注释第 11 行,自己看看。

文件名: BoxLayoutExample3.java

输出

BoxLayout class example

带有 PAGE_AXIS 的 BoxLayout 类的示例

以下示例显示了如何使用 PAGE_AXIS。

文件名: BoxLayoutExample4.java

输出

BoxLayout class example

上面的输出显示了按钮水平对齐。现在,我们将使用 PAGE_AXIS 垂直显示按钮。

文件名: BoxLayoutExample5.java

输出

BoxLayout class example
下一主题CardLayout