【Java AWT 图形界面编程】LayoutManager 布局管理器 ⑥ ( BoxLayout 布局 )

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6





一、BoxLayout 布局



BoxLayout 布局 不是 AWT 中的布局 , 而是 Swing 中引入的 ;

在 BoxLayout 布局 中 , 可以 在 垂直 和 水平 两个方向上 摆放 Component 组件 ;





二、BoxLayout 布局 API



BoxLayout 布局 API :

  • BoxLayout(Container target, int axis) : 为 Container target 组件 配置本 BoxLayout 布局管理器 , 该布局管理器会 按照指定的方向进行排列 , 垂直 或 水平方向 ;
    /**
     * 创建布局管理器该管理器将沿
     * 给定的轴。
     *
     * @param target  需要布置的容器
     * @param axis    沿轴线布置组件。可以是其中之一:
     *              <code>BoxLayout.X_AXIS</code>,
     *              <code>BoxLayout.Y_AXIS</code>,
     *              <code>BoxLayout.LINE_AXIS</code> or
     *              <code>BoxLayout.PAGE_AXIS</code>
     *
     * @exception AWTError  if the value of <code>axis</code> is invalid
     */
    @ConstructorProperties({"target", "axis"})
    public BoxLayout(Container target, int axis)




三、BoxLayout 布局代码示例



1、BoxLayout 布局垂直排列代码示例


代码示例 :

import javax.swing.*;
import java.awt.*;
import java.beans.ConstructorProperties;

public class HelloAWT {
    public static void main(String[] args) {
        // I. Frame 默认的布局管理器就是 BorderLayout
        Frame frame = new Frame("AWT 界面编程");

        // II. 为 Frame 配置 BoxLayout 布局管理器
        // 组件垂直摆放
        BoxLayout boxLayout = new BoxLayout(frame, BoxLayout.Y_AXIS);

        // 为容器设置布局管理器
        frame.setLayout(boxLayout);

        frame.add(new Button("按钮 1"));
        frame.add(new Button("按钮 2"));

        // III. 自定设置合适的大小
        frame.pack();
        frame.setVisible(true);
    }
}

执行效果 :

在这里插入图片描述

拖动放大后的效果 :

在这里插入图片描述


2、BoxLayout 布局水平排列代码示例


代码示例 :

import javax.swing.*;
import java.awt.*;
import java.beans.ConstructorProperties;

public class HelloAWT {
    public static void main(String[] args) {
        // I. Frame 默认的布局管理器就是 BorderLayout
        Frame frame = new Frame("AWT 界面编程");

        // II. 为 Frame 配置 BoxLayout 布局管理器
        // 组件垂直摆放
        BoxLayout boxLayout = new BoxLayout(frame, BoxLayout.Y_AXIS);

        // 为容器设置布局管理器
        frame.setLayout(boxLayout);

        frame.add(new Button("按钮 1"));
        frame.add(new Button("按钮 2"));

        // III. 自定设置合适的大小
        frame.pack();
        frame.setVisible(true);
    }
}

执行效果 :

在这里插入图片描述

放大后的效果 :
在这里插入图片描述

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java