由于仅贴出代码,供有缘人参考。
import java.awt.AlphaComposite; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.Timer; public abstract class Page extends JComponent implements ActionListener{ private static final long serialVersionUID = -1071441396934207094L; // 帧总量 private static final int FRAMES_COUNT=10; // Timer的时间间隔 private static final int INTERVAL=50; // 定时器 private Timer timer; // 每次递增或递减的值 private int offset=0; //帧索引 private int frameIndex; public void paint(Graphics g){ if(isTimerRunning()){ //根据当前帧显示当前透明度的内容组件 float alpha=(float)frameIndex/(float)FRAMES_COUNT; Graphics2D g2d=(Graphics2D)g; g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); //Renderer渲染机制 super.paint(g2d); }else{ super.paint(g); } } @Override public void actionPerformed(ActionEvent e) { //前进一帧 frameIndex+=offset; if(frameIndex>=FRAMES_COUNT || frameIndex<=0){ //最后一帧,关闭动画 closeTimer(); } else{ //更新当前一帧 repaint(); } } // 淡出 public boolean fadeOut(){ offset=-1; frameIndex=FRAMES_COUNT; timer=new Timer(INTERVAL,this); timer.start(); return true; } // 淡入 public boolean fadeIn(){ offset=1; frameIndex=0; timer=new Timer(INTERVAL,this); timer.start(); return true; } // 关闭定时器 protected void closeTimer(){ if(isTimerRunning()){ timer.stop(); timer=null; } } // 判断定时器是否处于工作状态 public boolean isTimerRunning(){ return timer!=null && timer.isRunning(); } }
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/xiandedanteng/p/3695268.html,如需转载请自行联系原作者