We all know the importance of user interface in any commercial as well as non commercial software. Today while working on one of my project I felt that the loading time of my application is quite longer than usual.
The reasons behind longer loading time are the loading of configuration file and downloading of resources from web. Here splash screen is the requirement for this situation.
Although there are many ways to implement splash screen in java but I prefer the built in API for
splash screen. Let's see how to use this native Splash screen API for your application.
Java SE 6 provides a solution that allows the application to display the splash screen much earlier, even before the virtual machine starts. A Java application launcher is able to decode an image and display it in a simple non-decorated window.
Below is the sample Java Swing application that do some time consuming task before initializing UI.
Copy and save below code in file
MySplashScreenDemo.java
package com.decryptoniter.splash;
import java.awt.FlowLayout;
import javax.swing.*;
public class MySplashScreenDemo {
MySplashScreenDemo() {
// some time consuming task before UI initialization
someTask();
// UI will initialize now
initUI();
}
void someTask() {
System.out.println("Some time consuming task is executed");
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
void initUI() {
JFrame frame = new JFrame("Splash Screen Demo");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("www.isumitjha.com");
panel.add(label);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
System.out.println("UI initialized");
}
public static void main(String s[]) {
MySplashScreenDemo ss = new MySplashScreenDemo();
}
}
Now compile MySplashScreenDemo.java:
javac -d . MySplashScreenDemo.java
Run this application:
java com.decryptoniter.splash.MySplashScreenDemo
You will notice that it takes 15 seconds to load the UI after running the application. Now to display splash screen while UI is not loaded we can use java command line argument.
Display a Splash Screen using the Command-Line Argument
To display a splash screen from the command line use the
-splash: command-line argument. This argument is a Java application launcher option that displays a splash screen:
java -splash:<file name> <class name>
For our application use.
java -splash:loading.gif com.decryptoniter.splash.MySplashScreenDemo
Now you can see the splash screen as soon as application is run while UI is not loaded.
Note: The splash screen can display any gif, png, or jpeg image, with transparency, translucency, and animation.