Fade out an image: image gradually get more transparent until it is completely invisible. : Swing Timer « Swing « Java Tutorial






import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class FadeOutImage extends JPanel implements ActionListener {
  Image myImage = new ImageIcon("a.jpg").getImage();

  Timer timer = new Timer(20, this);

  private float alpha = 1f;

  public FadeOutImage() {
    timer.start();
  }

  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;

    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    g2d.drawImage(myImage, 10, 10, null);
  }

  public void actionPerformed(ActionEvent e) {
    alpha += -0.01f;
    if (alpha <= 0) {
      alpha = 0;
      timer.stop();
    }
    repaint();
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Fade out");
    frame.add(new FadeOutImage());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 250);
    frame.setVisible(true);
  }

}








14.114.Swing Timer
14.114.1.Swing Timers
14.114.2.Timer Properties: coalesce
14.114.3.Timer Class
14.114.4.To turn on log messages
14.114.5.Timer based animation
14.114.6.A rotating and scaling rectangle.
14.114.7.Font size animation
14.114.8.Fade out an image: image gradually get more transparent until it is completely invisible.
14.114.9.Swing Timer actionSwing Timer action