java界面添加组件_java.awt 图形界面中给组件添加单色边框

在不使用swing包的情况下实现给awt包的组件添加模拟的单色边框。

把需要添加边框的组件添加到一个Panel中,给Panel设置背景颜色,把布局设置为GridBagLayout,用GridBagConstraints.insets来设置Panel和组件之间空隙的宽度,这个空隙和Panel的背景颜色构成包围组件的边框。

注意组件默认的背景颜色为透明,需要给组件设定与边框颜色不同的背景颜色。8b22ab26ef493287a87a82da4f4b89c6.png

供参考的部分代码:

import java.awt.Color;

import java.awt.Component;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.Insets;

import java.awt.Panel;

public class Border

{

public static Panel getPanel(Component component,Color color,int northWidth,int westWidth,int southWidth,int eastWidth)

{

GridBagConstraints gridBagConstraints=new GridBagConstraints();

gridBagConstraints.insets=new Insets(northWidth,westWidth,southWidth,eastWidth);

gridBagConstraints.fill=GridBagConstraints.BOTH;

gridBagConstraints.weightx=100;

gridBagConstraints.weighty=100;

Panel panel=new Panel(new GridBagLayout());

panel.setBackground(color);

panel.add(component,gridBagConstraints);

return panel;

}

}8b22ab26ef493287a87a82da4f4b89c6.png

public static void main(String[] args)

{

Frame frame=new Frame("test");

Label label=new Label("这是一个Label。边框颜色为黑色,上边框宽10,左边框宽5,下边框宽1,右边框宽0。");

frame.add(Border.getPanel(label,Color.BLACK,10,5,1,0));

label.setBackground(Color.YELLOW);

frame.setVisible(true);

}8b22ab26ef493287a87a82da4f4b89c6.png

效果:93ec77f69e85ca9d0d6b266b5592d55e.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值