Sep 27, 2012

How to Create your own Splash Screen in Java

Splash Screen
In this program, I will show you how to create your own Non-SDK Splash Screen. If you found the Java Splash Screen APIs hard to implement, this is a good choice for you.
Splash Screen is the short lived window that pops out in the middle of the computer or mobile device before the main program is fully loaded and lunched to the user. It mostly contains the progress of the loading components built in the program or just a logo of the software.
package codecypherprojects;

import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;

/**
 *
 * @author Khamis
 */

public class SplashScreen extends JWindow{
    JLabel splashImgHolder;
    Image image;
    ImageIcon splashIcon;
    JPanel contentPane;
    
    public SplashScreen(){
        image = new ImageIcon((getClass().getResource("/resource/cypher.png")))
        .getImage();
        splashIcon = new ImageIcon(image);
        
       /**
        * Enables the events defined by the specified event mask parameter to 
        * be delivered to this component. Event types are automatically enabled
        * when a listener for that event type is added to the component.
        */       
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        
        try{
            showSplash();
        }catch(Exception ex){
            System.out.println("Error! " + ex.getMessage());
            System.exit(1);
        }
        
        this.setVisible(true);
        
        try{
            Thread.sleep(5000);
        }catch(InterruptedException e){
            //do nothing here!
        }
    }


    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
    }
    private void showSplash() throws Exception{
        splashImgHolder = new JLabel();
        splashImgHolder.setIcon(splashIcon);
        
        contentPane = ((JPanel)this.getContentPane());
        contentPane.setLayout(new BorderLayout());
        contentPane.add(splashImgHolder, BorderLayout.NORTH);
        
        setSplashLocation();
        
        pack();
        
    }

    private void setSplashLocation() {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frame = this.getSize();     
        
        int x = (int)(screen.getWidth() - frame.getWidth())/2;
        int y = (int)(screen.getHeight() - frame.getHeight())/2 - 50;
        
        this.setLocation(x, y);
    }
    public static void main(String[] arg){
        SplashScreen splash = new SplashScreen();
        //get rid of window as it finished showing
        splash.dispose();
    }
}

Related Posts 

 



2 comments:

  1. People like you , if assisted and encouraged, you will certainly excel and make a tremendous difference in the society.There4, keep on striving ,expanding and watering your talent-sky will be your starting point. :)
    Rabiu .M.M.

    ReplyDelete