Fade Effect for JLabel using Timer

Have you ever tried fading out a JLabel or a component from transparency to semi transparency and then to pure opacity. This is very simple using the Timer class. The image on the side, is just a mere sample output, but the program's output is much more beautiful. In this I have applied fade effect for both foreground and background. Saying more is useless, see it in action instead.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.image.*;
class FadeJLabel extends JFrame
{
JLabel l;
ImageIcon icon;
Timer t;
int x;

    public FadeJLabel()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        // Set frame properties
        setTitle("Fade JLabel");
        setLayout(new GridBagLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // Set a white background for the JFrame
        getContentPane().setBackground(Color.WHITE);
       
        // Create an ImageIcon
        icon=new ImageIcon("D:\\Documents and Settings\\Gutha\\My Documents\\Downloads\\cloud_icon.png");       
       
        // Create a JLabel
        l=new JLabel("Java-Demos.blogspot.com");
       
        // Set the text position bottom center relative
        // to the icon so that the icon appears as a
        // a desktop icon
        l.setVerticalTextPosition(SwingConstants.BOTTOM);
        l.setHorizontalTextPosition(SwingConstants.CENTER);
       
        // Set the icon to the JLabel
        l.setIcon(icon);
       
        // Set foreground
        l.setForeground(new Color(0,0,0,0));
       
        l.setOpaque(true);
       
        // Set some font
        l.setFont(new Font("Myriad Pro",Font.PLAIN,28));
       
        // Add the JLabel
        add(l);
           
        // Create a Timer with that executes
        // each 1ms
        t=new Timer(10,new ActionListener(){
       
            public void actionPerformed(ActionEvent ae)
            {
                // Increase the alpha value by time
                // so that transparency decreases for each
                // actionPerformed() call
                l.setForeground(new Color(0,0,0,x++));
                l.setBackground(new Color(255,255,255,x));
                if(x==255) t.stop();
            }
        });
       
        // Set some initial delay, optional
        t.setInitialDelay(200);
       
        // Start the timer
        t.start();
       
        // Set size and show the frame
        setSize(500,500);
        setVisible(true);
        setLocationRelativeTo(null);
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new FadeJLabel();
            }
        });
    }
}

You might also like animating JFrame with random colors and create a moving JFrame in swing. Do not hesitate to drop a comment.

No comments: