java中自定义边框-创新互联
                                            自定义边框,可以继承AbstractBorder,需要实现三个方法

public boolean isBorderOpaque() 此默认实现返回false。 public Insets getBorderInsets(Component c)此默认实现返回一个新Insetspublic void paintBorder(Component c, Graphics g, int x, int y, int width, int height) 绘制边框
绘制边框最主要是不要在组件区域内绘制边框,在给定的范围内绘制。如下图:

在JComponent中画边框调用的代码,传入的是组件的宽和高,起点是0,0,所以说边框的厚度在组件的宽高范围内。
protected void paintBorder(Graphics g) {
        Border border = getBorder();
        if (border != null) {
            border.paintBorder(this, g, 0, 0, getWidth(), getHeight());
        }
    }自定义了一个边框,上下一个颜色,左右黑色的。代码如下:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.border.AbstractBorder;
public class MyBorder extends AbstractBorder
{
	private int thickless;
	private Color color;
	
	public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
	{
		Insets insets = getBorderInsets(c);
		Color c1 = g.getColor();
		g.setColor(color);
		g.fillRect(x, y, width, insets.top);
		g.fillRect(x, y + height-insets.bottom, width, insets.bottom);
		g.setColor(Color.BLACK);
		g.fillRect(x, y + insets.top, x+insets.left, y + height-insets.top);
		g.fillRect(x+width-insets.right, y+insets.top, insets.right, height-insets.top-insets.bottom);
		g.setColor(c1);
	}
	public MyBorder(int thickless, Color color)
	{
		super();
		this.thickless = thickless;
		this.color = color;
	}
	@Override
	public Insets getBorderInsets(Component c)
	{
		
		return new Insets(thickless,thickless,thickless,thickless);
	}
	@Override
	public boolean isBorderOpaque()
	{
		
		return true;
	}
}测试代码如下:
JPanel jpa = new JPanel(new GridLayout(1,2));
		jpa.setPreferredSize(new  Dimension(400,80));
		MyBorder eb = new MyBorder(5,Color.red);
		MyBorder eb1 = new MyBorder(10,Color.BLUE);
		JButton jb = new JButton("red");
		jb.setBorder(eb);
		jpa.add(jb);
		JButton jb1 = new JButton("blue");
		jb1.setBorder(eb1);
		jb1.setSize(150,80);
		jpa.add(jb1);
		add(jpa);效果如下:

由于水平有限,如果有错误,请大家多多指导,提高水平,共同学习。
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
本文名称:java中自定义边框-创新互联
转载来源:http://www.scyingshan.cn/article/dihogs.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 