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);

效果如下:

 由于水平有限,如果有错误,请大家多多指导,提高水平,共同学习。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值