java学习——51.边布局
边布局是框架Frame、JFrame的默认布局方式。
BorderLayout布局是将容器划分为5个区域:东、南、西、北、中,组件占满一条边或中间部分。
当容器大小改变时,四边不变,中间组件的长度和宽度将随容器大小而变化。
BorderLayout类声明如下:
public class BorderLayout implements LayoutManager2,java.io.Serializable
{
public static final String NORTH = "North"; //北
public static final String SOUTH = "South";//南
public static final String EAST = "East";//东
public static final String WEST = "West";//西
public static final String CENTER = "Center"; //注意,字符串首字母大写
public BorderLayout() //构造方法
}
在使用时,用add方法为其添加组件。
如:add(new Button(“0”,BorderLayout.EAST);
或add(new Button(“0”,”South”);
均可。
以上篇中的例题部分组件为例,改变其布局方式为边布局,代码如下:
import java.awt.*;
import java.awt.event.*;
public class Login extends Frame{
public static void main(String args[]){
Login l=new Login();
l.setTitle("计算器");
l.setSize(200,200);
l.setLocation(200,200);
l.setVisible(true);
l.setResizable(false);
l.setLayout(new BorderLayout());
Label label=new Label("请输入:");
l.add(label,BorderLayout.EAST);
TextField t=new TextField(10);
l.add(t,"South");
Button b1=new Button("1");
Button b10=new Button("0");
l.add(b1,"North");
l.add(b10,"West");
Button b=new Button("确定");
l.add(b);
l.addWindowListener(new WinClose());
}
}
class WinClose implements WindowListener{
publicvoid windowClosing(WindowEvent ev){
System.exit(0);
}
publicvoid windowOpened(WindowEvent ev){}
publicvoid windowActivated(WindowEvent ev){}
publicvoid windowDeactivated(WindowEvent ev){}
publicvoid windowClosed(WindowEvent ev){}
publicvoid windowIconified(WindowEvent ev){}
publicvoid windowDeiconified(WindowEvent ev){}
}
其运行结果如下:
注:东南西北中每个位置只能放一个组件,如果放置了多个组件,在显示时只会显示最后加的那一个。