Tym-Project

From: SUPINFO
To: Tous
Subject: IT

Fade-in/Fade-out Effect With Java

A nice face-in when a text appears is developer’s drug…but how is it possible to achieve that using Java/Swing?

The easiest way I found (there must be others!) is to use AWTUtilities (to handle transparency) and a Timer (for step by step in or out effect).

As an example, let’s use a JDialog which we are going to fade-out, until it’s full disappearance. It’s literally a “splash screen”.

Java is objet oriented (who isn’t nowadays…), so let’s create a class dedicated to fade-out :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.TimerTask;
import javax.swing.JDialog;
import com.sun.awt.AWTUtilities;

public class Fader extends TimerTask {

    private JDialog jDialog;

    public Fader(JDialog jDialog) {
        this.jDialog = jDialog;
    }
    //As Fader extends from Timer, it's the run() method which does the main job
    @Override public void run() {
        //The opacity is reduced by 0,01f steps
        //If this value equals 0 (invisible), we close the JDialog with dispose()
    if(AWTUtilities.getWindowOpacity(jDialog) > 0.01f){
        AWTUtilities.setWindowOpacity(jDialog,
        AWTUtilities.getWindowOpacity(jDialog)-0.01f);
    }
    else {
        jDialog.dispose();
    }
    }
}

And the class containing our JDialog:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Timer;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Splash extends JDialog {

    public Splash() { //The JDialog will be in the center of the screen
        setLocationRelativeTo(null);

        //Title bar is deactivated setUndecorated(true);

        JPanel main = new JPanel(new GridLayout(1, 1));
        JLabel label = new JLabel("Hello Kitty !");

        //We write in BIG LETTERS, the farthest it's seen the better!
        label.setFont(new Font("Arial",Font.BOLD, 20);

        this.add(main); main.add(label); this.setVisible(true); pack();

        //We instanciate the Timer Timer timer = new Timer();

        //And then we launch the fade-out, waiting 500ms before starting
        //Then we gradually fade out every 5ms
        timer.schedule(new Fader(this),500, 5);
    }
}

For testing you can use a call like that:

1
new Splash();

Enjoy your Swing ;-)

Comments