GUI编程核心技术AWT——三种布局管理器
流式布局(FlowlLayout)
public class TestFlowl {public static void main(String[] args) {Frame frame = new Frame(\"有按钮的窗口\");//组件——按钮Button button1 = new Button(\"Button1\");Button button2 = new Button(\"Button2\");Button button3 = new Button(\"Button3\");//设置流式布局frame.setLayout(new FlowLayout());//默认位置居中//frame.setLayout(new FlowLayout(FlowLayout.LEADING));//frame.setLayout(new FlowLayout(FlowLayout.LEFT)); 左//frame.setLayout(new FlowLayout(FlowLayout.RIGHT)); 右// frame.setLayout(new FlowLayout(FlowLayout.TRAILING));frame.setBounds(300,300,600,600);frame.setBackground(new Color(11,34,56));frame.setVisible(true);//把按钮添加上去frame.add(button1);frame.add(button2);frame.add(button3);//监听事件,监听窗口关闭事件 System.exit(0)强制结束//适配器模式frame.addWindowListener(new WindowAdapter() {//点击窗口关闭要做的事情@Overridepublic void windowClosing(WindowEvent e) {//结束程序System.exit(0);}});}}
效果图
东西南北中布局(BorderLayout)
//设置东西南北中布局//布局是可以嵌套使用的,比如东西南北中布局中可以嵌套使用流式布局public class TestBorderLayout {public static void main(String[] args) {Frame frame = new Frame(\"TestBorderLayout窗口\");//设置东西南北中布局//定义按钮Button east = new Button(\"East按钮\");Button west = new Button(\"West按钮\");Button south = new Button(\"South按钮\");Button north = new Button(\"North按钮\");Button center = new Button(\"Center按钮\");//设置按钮在窗口的位置frame.add(east,BorderLayout.EAST);frame.add(west,BorderLayout.WEST);frame.add(south,BorderLayout.SOUTH);frame.add(north,BorderLayout.NORTH);frame.add(center,BorderLayout.CENTER);frame.setBounds(300,300,600,600);frame.setVisible(true);frame.setBackground(new Color(1,1,1));//监听事件,监听窗口关闭事件 System.exit(0)强制结束//适配器模式frame.addWindowListener(new WindowAdapter() {//点击窗口关闭要做的事情@Overridepublic void windowClosing(WindowEvent e) {//结束程序System.exit(0);}});}}
效果图
表格布局(GridLayout)
//设置表格布局public class TestGridLayout {public static void main(String[] args) {Frame frame = new Frame(\"TestGridLayout表格布局窗口\");Button button1 = new Button(\"btn1\");Button button2 = new Button(\"btn2\");Button button3 = new Button(\"btn3\");Button button4 = new Button(\"btn4\");Button button5 = new Button(\"btn5\");Button button6 = new Button(\"btn6\");//设置一个三行两列的表格frame.setLayout(new GridLayout(3,2));//填充按钮,表格会自动填充frame.add(button1);frame.add(button2);frame.add(button3);frame.add(button4);frame.add(button5);frame.add(button6);frame.setVisible(true);frame.pack();//java函数,会自动的选择最优秀的位置进行布局frame.setBackground(new Color(1,1,1));frame.setBounds(300,300,600,600);//监听事件,监听窗口关闭事件 System.exit(0)强制结束//适配器模式frame.addWindowListener(new WindowAdapter() {//点击窗口关闭要做的事情@Overridepublic void windowClosing(WindowEvent e) {//结束程序System.exit(0);}});}}
效果图