注释很详细,直接上代码
package swing21_30;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class swing_test_26 {
JFrame jFrame = new JFrame("测试边框");
public void init(){
//设置Jframe为网格布局
jFrame.setLayout(new GridLayout(2,4));
//1.BevelBorder
//创建凸起的斜边框,分别设置四条边的颜色
// 参数分别为:边框类型,上边框颜色,下边框颜色,左边框颜色,右边框颜色
Border bevelBorder = BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.RED,Color.GREEN,Color.BLUE,Color.GRAY);
jFrame.add(getPanelWithBorder(bevelBorder,"BevelBorder"));//添加到窗体
//2.LineBorder
//创建LineBorder
// 参数分别为:边框颜色,边框宽度
Border lineBorder = BorderFactory.createLineBorder(Color.ORANGE, 10);
jFrame.add(getPanelWithBorder(lineBorder,"LineBorder"));
//3.EmptyBorder
//创建EmptyBorder,会在组件的四周留白
// 参数分别为:上边框宽度,左边框宽度,下边框宽度,右边框宽度
Border emptyBorder = BorderFactory.createEmptyBorder(20, 5, 10, 30);
jFrame.add(getPanelWithBorder(emptyBorder,"EmptyBorder"));
//4.EtchedBorder
//创建EtchedBorder,它是虚线边框
// 参数分别为:边框样式,边框前景色,边框背景色
Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.RED, Color.GREEN);
jFrame.add(getPanelWithBorder(etchedBorder,"EtchedBorder"));
//5.TitledBorder
//创建TitledBorder,为原有的Border添加标题
// 参数分别为:原先边框,标题位置(水平),标题位置(垂直),标题字体类型,标题字体颜色
TitledBorder titledBorder = new TitledBorder(lineBorder,"测试标题",TitledBorder.LEFT,TitledBorder.BOTTOM,new Font("StSong",Font.BOLD,18),Color.BLUE);
jFrame.add(getPanelWithBorder(titledBorder,"TitledBorder"));
//6.MatteBorder
//直接创建MatteBorder,它是EmptyBorder的子类,EmptyBorder是留白,而MatteBorder可以给留空的区域填充颜色
// 参数分别为:上边框宽度,左边框宽度,下边框宽度,右边框宽度,边框颜色
MatteBorder matteBorder = new MatteBorder(20,5,10,30,Color.GREEN);
jFrame.add(getPanelWithBorder(matteBorder,"MatteBorder"));
//7.CompoundBorder
//直接创创建CompoundBorder,将两个边框组合成新边框
// 参数分别为:外边框,内边框
CompoundBorder compoundBorder = new CompoundBorder(new LineBorder(Color.RED,8),titledBorder);
jFrame.add(getPanelWithBorder(compoundBorder,"CompoundBorder"));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.pack();
jFrame.setVisible(true);
}
//创建JPanel,并设置边框与文字
public JPanel getPanelWithBorder(Border border,String borderName){
JPanel jPanel = new JPanel();//创建JPanel
jPanel.add(new JLabel(borderName));//添加文字
//为panel设置边框
jPanel.setBorder(border);
return jPanel;//返回JPanel
}
public static void main(String[] args) {
//创建测试对象
new swing_test_26().init();
}
}
效果演示: