首页 > 技术文章 > 三种布局管理器

lysstudy 2021-07-18 11:11 原文

一、FlowLayout 浮动布局

package com.sheng.lesson01;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestFlowLayout {
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(FlowLayout.LEFT));

frame.setSize(400,400);

frame.add(button1);
frame.add(button2);
frame.add(button3);

frame.setVisible(true);

frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
}

 

 

二、BorderLayout 边界布局

package com.sheng.lesson01;

import java.awt.*;

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.setSize(400,400);
frame.setVisible(true);
}
}

 

 

三、GridLayout 网格布局

package com.sheng.lesson01;

import java.awt.*;

public class TestGridLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestBorderLayout");

Button btn1 = new Button("btn1");
Button btn2 = new Button("btn2");
Button btn3 = new Button("btn3");
Button btn4 = new Button("btn4");
Button btn5 = new Button("btn5");
Button btn6 = new Button("btn6");

frame.setLayout(new GridLayout(3,2));

frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.add(btn6);

frame.pack();//自动布局最优位置
frame.setVisible(true);
}
}

 四、思考题

 

推荐阅读