这里介绍3种布局:
- FlowLayout 流式布局
- BorderLayout 边界布局
- GridLayout 网格布局
FlowLayout
/*MyFrame定义见 Java笔记9,这里添加了事件监听方法*/
public class TestFlowLayout {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame(300, 300, 500, 500, Color.GRAY);
//组件--按钮
Button button1 = new Button("Button1");
Button button2 = new Button("Button2");
Button button3 = new Button("Button3");
myFrame.setLayout(new FlowLayout(FlowLayout.TRAILING));//添加默认的流式布局的中间位置
myFrame.add(button1);
myFrame.add(button2);
myFrame.add(button3);
}
}
BorderLayout
public class TestBorderLayout {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame(300, 300, 400, 300, Color.GRAY);
myFrame.setLayout(new BorderLayout());//设置BorderLayout
//设置五个按钮
Button button1 = new Button("Center button");
Button button2 = new Button("North button");
Button button3 = new Button("South button");
Button button4 = new Button("West button");
Button button5 = new Button("East button");
//将按钮添加到Frame中时,指定在组件中的位置
myFrame.add(button1, BorderLayout.CENTER);
myFrame.add(button2, BorderLayout.NORTH);
myFrame.add(button3, BorderLayout.SOUTH);
myFrame.add(button4, BorderLayout.WEST);
myFrame.add(button5, BorderLayout.EAST);
}
}
GridLayout网格布局
public class TestGridLayout {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame(300, 300, 400, 300, Color.GRAY);
myFrame.setLayout(new GridLayout(2, 3, 20, 10));
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
Button button4 = new Button("button4");
Button button5 = new Button("button5");
Button button6 = new Button("button6");
myFrame.add(button1);
myFrame.add(button2);
myFrame.add(button3);
myFrame.add(button4);
myFrame.add(button5);
myFrame.add(button6);
//myFrame.pack();//自动优化布局,会把布局缩小到尽量小
}
}
标签:10,Java,300,GUI,BorderLayout,add,new,Button,myFrame
From: https://www.cnblogs.com/hiibird/p/17290029.html