How can we implement a splash screen using JWindow in Java?


A JWindow is a container that can be displayed anywhere on the user desktop. It does not have the title bar, window management buttons, etc like a JFrame.

The JWindow contains a JRootPane as its only child class. The contentPane can be the parent of any children of the JWindow. Like a JFrame, a JWindow is another top-level container and it is as an undecorated JFrame. It does not have features like a title bar, windows menu, etc. A JWindow can be used as a splash screen window that displays once when the application is launched and then automatically disappears after a few seconds.

Example

import javax.swing.*;
import java.awt.*;
public class CreateSplashScreen extends JWindow {
   Image splashScreen;
   ImageIcon imageIcon;
   public CreateSplashScreen() {
      splashScreen = Toolkit.getDefaultToolkit().getImage("C:/Users/User/Desktop/Java                Answers/logo.jpg");
      // Create ImageIcon from Image
      imageIcon = new ImageIcon(splashScreen);
      // Set JWindow size from image size
      setSize(imageIcon.getIconWidth(),imageIcon.getIconHeight());
      // Get current screen size
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      // Get x coordinate on screen for make JWindow locate at center
      int x = (screenSize.width-getSize().width)/2;
      // Get y coordinate on screen for make JWindow locate at center
      int y = (screenSize.height-getSize().height)/2;
      // Set new location for JWindow
      setLocation(x,y);
      // Make JWindow visible
      setVisible(true);
   }
   // Paint image onto JWindow
   public void paint(Graphics g) {
      super.paint(g);
      g.drawImage(splashScreen, 0, 0, this);
   }
   public static void main(String[]args) {
      CreateSplashScreen splash = new CreateSplashScreen();
      try {
         // Make JWindow appear for 10 seconds before disappear
         Thread.sleep(10000);
         splash.dispose();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Updated on: 07-Feb-2020

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements