Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java: How to fade out an image

Java: How to fade out an image

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.*;
public class ImageFadOut extends JPanel implements ActionListener
  Image img;
  Timer timer = new Timer(20, this);
  private float alpha = 1f;
  public ImageFadOut()
    if(img !=null)
 private Image getImage()  // select an image
 	JFileChooser chooser = new JFileChooser();
 	chooser.setDialogTitle("Sélectionner une image");
    int returnVal = chooser.showOpenDialog(null);
    String imgURL="";
    if(returnVal == JFileChooser.APPROVE_OPTION) 
    	imgURL=	chooser.getSelectedFile().getAbsolutePath();
       return new ImageIcon(imgURL).getImage();
  public void paint(Graphics g)
    Graphics2D g2d = (Graphics2D) g;
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    g2d.drawImage(img, 10, 10, null);
  public void actionPerformed(ActionEvent e)
    alpha += -0.01f;
    if (alpha <= 0) {
      alpha = 0;
  public static void main(String[] args) {
    JFrame frame = new JFrame("Animation And Transparency");
    frame.add(new ImageFadOut());
    frame.setSize(350, 300);

Users who found this page were searching for:

  • java graphics arc2d
  • write a program that displays the calender java jpanel gridlayout
  • perl print out all words in file
  • list .replace python

No comments yet.

Leave a Comment