一个可以淡入淡出的JButton

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;


public class ZButton extends JButton{
	private static final long serialVersionUID = 1L;
	
	private int delay=5;//时间控件时间间隔
	private Timer time=new Timer(delay,new TimeListener());
	private float alpha=1.0f;
	private BufferedImage buttonImage=null;
	private boolean isShow=false;//指出当前状态是否可见
	
	public ZButton(String name){
		super(name);//调用父类的构造函数来设置button上显示的文字
		this.setOpaque(false);//设置button的不透明属性改成false
		this.addMouseListener(new HoverListener());
	}

	//覆盖JButton的paint的方法
	public void paint(Graphics g){
		if(buttonImage == null || buttonImage.getHeight() != this.getHeight() || buttonImage.getWidth() != this.getWidth()){
			buttonImage=this.getGraphicsConfiguration().createCompatibleImage(this.getWidth(), this.getHeight());
		}
		Graphics gButton=buttonImage.getGraphics();
		gButton.setClip(g.getClip());//只显示图片中和按钮一样大小的那一部分被截取的图像部分
		super.paint(gButton);
		Graphics2D g2D=(Graphics2D)g;
		AlphaComposite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,alpha);
		g2D.setComposite(newComposite);
		g2D.drawImage(buttonImage,0,0,null);
	}
	
	private class TimeListener implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			// TODO 自动生成方法存根
			if(isShow){
				alpha+=0.01f;
				if(alpha >= 1.0f){
					alpha=1.0f;
					time.stop();
				}
				repaint();
			}else{
				alpha-=0.01f;
				if(alpha <= 0.0f){
					alpha=0.0f;
					time.stop();
				}
				repaint();
			}
		}
	}
	
	private class HoverListener extends MouseAdapter{

		public void mouseEntered(MouseEvent e) {
			// TODO 自动生成方法存根
			time.start();
			isShow=true;
		}

		public void mouseExited(MouseEvent e) {
			// TODO 自动生成方法存根
			time.start();
			isShow=false;
		}
	}
}




附件为打包成jar包以及源码

你可能感兴趣的:(swing)