一个可以淡入淡出的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包以及源码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值