在不使用swing包的情况下实现给awt包的组件添加模拟的单色边框。
把需要添加边框的组件添加到一个Panel中,给Panel设置背景颜色,把布局设置为GridBagLayout,用GridBagConstraints.insets来设置Panel和组件之间空隙的宽度,这个空隙和Panel的背景颜色构成包围组件的边框。
注意组件默认的背景颜色为透明,需要给组件设定与边框颜色不同的背景颜色。
供参考的部分代码:
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;
}
}
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);
}
效果: