Java中利用Swing构建一个简单的窗口(四)——使用BorderLayout布局
作者:互联网
简介
BorderLayout把容器分成五个部分:东南西北中,用add(Component,index)方法可以把组件添加到BorderLayout之中,index的取值有BorderLayout.EAST,BorderLayout.NORTH,BorderLayout.WEST,BorderLayout.SOUTH,BorderLayout.CENTER。
效果
代码
package Test;
import javax.swing.*;
import java.awt.*;
public class TestFrame extends JFrame{
public TestFrame(){
setLayout(new BorderLayout(5,10));
add(new JButton("East"),BorderLayout.EAST);
add(new JButton("North"),BorderLayout.NORTH);
add(new JButton("West"),BorderLayout.WEST);
add(new JButton("South"),BorderLayout.SOUTH);
add(new JButton("Center"),BorderLayout.CENTER);
}
public static void main(String[] args) {
TestFrame frame=new TestFrame();
frame.setTitle("ShowBorderLayout");
frame.setSize(300,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
public TestFrame(){
setLayout(new BorderLayout(5,10));
add(new JButton("East"),BorderLayout.EAST);
add(new JButton("North"),BorderLayout.NORTH);
add(new JButton("West"),BorderLayout.WEST);
add(new JButton("South"),BorderLayout.SOUTH);
}
public static void main(String[] args) {
TestFrame frame=new TestFrame();
frame.setTitle("ShowBorderLayout");
frame.setSize(300,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
注意
如果把东区删除,会发现中区会向右延伸占据东区,效果如下:
标签:BorderLayout,frame,Swing,TestFrame,add,new,Java,JButton 来源: https://blog.csdn.net/qq_43576028/article/details/100800641