Java 的一些常用自定义方法 Utils

得到Exception详细信息

	//跟踪Exception信息,将其返回
	public static String getStackTraceString(Exception e){
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		return sw.toString();
	}

由于printStackTrace()方法没有返回值,所以要自定义方法返回内容。此方法可以用户返回exception的详细错误。

有些时候,我们在Swing中用到类似于HTML的遮罩效果,但是目前在Swing中还没有特别好的面板组件半透明效果(com.sun.awt.AWTUtilities.setWindowOpacity()是针对window的)。

在此提供一个类似于遮罩的方法。将你所要获取的遮罩背景作为一张图片,并加入混合色效果

    public static Image getMaskScreenShot(Component component,final Color maskColor, final int percent){
        BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
        component.paint(image.getGraphics());
        //把图片和遮罩颜色进行混合
        ImageProducer prod = new FilteredImageSource(image.getSource(), new RGBImageFilter() {
            @Override
            public int filterRGB(int x, int y, int rgb) {
                Color c = new Color(rgb);
                int r = calculate(maskColor.getRed(), c.getRed());
                int g = calculate(maskColor.getGreen(), c.getGreen());
                int b = calculate(maskColor.getBlue(), c.getBlue());
                
                return (0xFF)<<24 | (r & 0xFF)<<16 | (g & 0xFF)<<8 | (b & 0xFF)<<0;
            }
            private int calculate(int maskValue, int value){
                return (maskValue*percent + value*(100-percent))/100;
            }
        });
        return Toolkit.getDefaultToolkit().createImage(prod);
    }
欢迎加入我的QQ群(JAVA开发):216672921,程序 元 世界
原文地址:https://www.cnblogs.com/icerainsoft/p/2720115.html