java swing设置组件圆角边框并透明

最近在研究JButton和JLabel组件实现圆角边框并透明,不想重写JBubtton和JLabel,觉得太麻烦,想写一个通用的LineBorder类。思路是根据边框厚度和颜色,在原组件上绘制内外圆角矩形,然后填充两个边框之间的矩形形成边框,最后将组件原来的油漆区剪辑为外圆角矩形或者内圆角矩形都可以,让圆角之外的区域直接失效达到透明效果,这个思路应该对图片按钮也应该有效,免去P图玛法。但是在处理组件原来的油漆区时无效,获取的油漆区是null。还想到的将g的剪辑区域设置好后,在paintBorder函数最后用c.update(g)重绘c,但是一直闪烁,程序进入死循环并报错。具体代码如下:

package com.java.Myswing;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Path2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.border.LineBorder;

public class SoftBorder extends LineBorder {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1733648128327385862L;
	Color color;
	int soft;
	int thickness;
	Shape outer;
	Shape inner;

	public SoftBorder(Color color, int thickness, int soft) {
		/**
		 * @param color
		 *            边框颜色
		 * @param thickness
		 *            边框厚度
		 * @param softnum
		 *            圆角半径
		 */
		super(color, thickness);
		this.soft = soft;
		this.color = color;
		this.thickness = thickness;
	}

	public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {


		outer = new RoundRectangle2D.Float(x, y, width, height, soft, soft);//外边框形状
		inner = new RoundRectangle2D.Float(x + thickness, x + thickness, width - 2 * thickness, height - 2 * thickness,
				soft - thickness, soft - thickness);//内边框形状
		
		Graphics2D g2d = (Graphics2D) g;
		g.setColor(this.lineColor);
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//抗锯齿
		Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD);
		path.append(outer, false);
		path.append(inner, false);
		g2d.fill(path);//填充边框
		c.getGraphics().setClip(null);//清除组件原来的剪辑区域
		System.out.println("--原始剪辑区域:"+c.getGraphics().getClip());
		c.getGraphics().setClip(inner);//重设原来的剪辑区域,内边框形状之外的部分失效
		System.out.println("--剪辑区域:"+c.getGraphics().getClip());
	}
	
}

paintBorder里面的graphics应该不是c的 graphics,但是获取c的graphics又为空,怎么办啊。测试结果:

java swing设置组件圆角边框并透明_第1张图片

 

java swing设置组件圆角边框并透明_第2张图片

你可能感兴趣的:(java swing设置组件圆角边框并透明)