Monday, October 13, 2014

Old Java Swing style fadeIn / fadeOut on image

As my open source project (Violet UML Editor) has a GUI developed in Swing (wich is not a problem because I massively use the Graphics2D canvas which should be portable to other tehnologies), I sometimes have to find tricks to enhance UX. That was my last challenge. I decided to implement fade effects on image. After googlings, I didn't find anything ready to use. So, I developed a quick and simple piece of code I share with you. The idea is to embed my image as an ImageIcon attached to a JLabel. Then, to trigger fade effects, I just use a mouse listener.

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.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Timer;

public class FadeImage extends JLabel implements ActionListener {

    // Up to 1f
    private float opacity = 0f;
    private Timer fadeTimer;
    private int fadeIndicator = 1;

    public FadeImage(ImageIcon anImage) {
super();
setIcon(anImage);
initializeTimer();
    }

    private void initializeTimer() {
fadeTimer = new javax.swing.Timer(75, this);
fadeTimer.setInitialDelay(0);
    }

    public void fadeIn() {
fadeIndicator = 1;
fadeTimer.restart();
    }

    public void fadeOut() {
fadeIndicator = -1;
fadeTimer.restart();
    }

    public void actionPerformed(ActionEvent e) {
opacity = opacity + (fadeIndicator * 0.1f);
if (opacity > 1) {
   opacity = 1;
   fadeTimer.stop();
}
if (opacity < 0) {
   opacity = 0;
   fadeTimer.stop();
}
repaint();
    }

    @Override
    public void paint(Graphics g) {
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
super.paint(g);
    }

}


Here is an example of the mouse listener :


           
                       final FadeImage fadeImage = new FadeImage(this.rightPanelIcon);
            this.rightTitlePanel.add(fadeImage);
            getLeftTitlePanel().addMouseListener(new MouseListener() {
       
       @Override
       public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub
       }
       
       @Override
       public void mousePressed(MouseEvent e) {
    // TODO Auto-generated method stub
       }
       
       @Override
       public void mouseExited(MouseEvent e) {
       fadeImage.fadeOut();
       }
       
       @Override
       public void mouseEntered(MouseEvent e) {
       fadeImage.fadeIn();
       }
       
       @Override
       public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub
       }
   });



Quite simple and easy!

1 comment:

simashree said...

Thanks for the great information in your blog Selenium Training in Chennai