background image

9

b.setLocation(40, 60);

//x 坐标 40,y 坐标 60

10

f.add(b);

11

f.setVisible(

true

);

12

}

13

}

-----------------------------------------------------------------------------------------------------------------------------------------
---------------------
FlowLayout 流式布局管理器

FlowLayout 按照组件的添加次序将它们从左到右地放置在容器中。当到达容器边界时,组件将放置在下一

行中。

FlowLayout 允许左对齐、居中对齐(默认方式)或右对齐的方式排列组件。FlowLayout 有以下特性:

不限制它所管理的组件的大小,而是允许它们有自己的最佳大小。

当容器被缩放时,组件的位置可能会变化,但组件的大小不会改变。

FlowLayout 的构造方法如下:

FlowLayout()

FlowLayout(int align)

FlowLayout(int align, int hgap, int vgap)

参数

align 用来决定组件在每行中相对于容器的边界的对齐方式,可选值有:

FlowLayout.LEFT 左对齐

FlowLayout.RIGHT 右对齐

FlowLayout.CENTER 居中对齐

参数

hgap 和参数 vgap 分别设定组件之间的水平和垂直间隙。

【例程】

FlowLayoutDemo 类中,Frame 采用 FlowLayout 布局,在 Frame 中加入了 3 个 Button,单击

leftButton 按钮,就会采用左对齐方式,单击 centerButton 按钮,就会采用居中对齐方式,单击 rightButton
按钮,就会采用右对齐方式。

1

import

 java.awt.*;

2

import

 java.awt.event.*;

3

public

 

class

 FlowLayoutDemo {

4

public

 

static

 

void

 main(String[] args){

5

final

 Frame f = 

new

 Frame(

"hello"

);

6

final

 FlowLayout fl = 

new

 FlowLayout();

7

f.setLayout(fl);

8

//单击则左对齐

9

Button leftButton = 

new

 Button(

"left"

);

10

leftButton.addActionListener(

new

 ActionListener(){

//注册事件监听器

11

public

 

void

 actionPerformed(ActionEvent event){

12

fl.setAlignment(FlowLayout.

LEFT

);

//左对齐

13

fl.layoutContainer(f);

//使 Frame 重新布局

14

}

15

});

16

//单击则居中对齐

17

Button centerButton = 

new

 Button(

"center"

);

18

centerButton.addActionListener(

new

 ActionListener(){

//注册事件监听器

19

public

 

void

 actionPerformed(ActionEvent event){

20

fl.setAlignment(FlowLayout.

CENTER

);

//居中对齐

21

fl.layoutContainer(f);

//使 Frame 重新布局

22

}

23

});