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 :
123456789101112131415161718192021222324
importjava.util.TimerTask;importjavax.swing.JDialog;importcom.sun.awt.AWTUtilities;publicclassFaderextendsTimerTask{privateJDialogjDialog;publicFader(JDialogjDialog){this.jDialog=jDialog;}//As Fader extends from Timer, it's the run() method which does the main job@Overridepublicvoidrun(){//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:
1234567891011121314151617181920212223242526272829
importjava.awt.Font;importjava.awt.GridLayout;importjava.util.Timer;importjavax.swing.JDialog;importjavax.swing.JLabel;importjavax.swing.JPanel;publicclassSplashextendsJDialog{publicSplash(){//The JDialog will be in the center of the screensetLocationRelativeTo(null);//Title bar is deactivated setUndecorated(true);JPanelmain=newJPanel(newGridLayout(1,1));JLabellabel=newJLabel("HelloKitty!");//We write in BIG LETTERS, the farthest it's seen the better!label.setFont(newFont("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 5mstimer.schedule(newFader(this),500,5);}}