Search code examples
javasplash-screen

Dynamic splash screens for my java application


I want to create a splash screen for my Java application. I managed to do this using the NetBeans default tool that allows me to put some image in. But i want to have something "live" there, such as a progress bar showing the status of application load, some dynamic text, etc.

How do I do this? What are the things I need to know to start doing something like this?


Solution

  • The trick is to create a splash screen using swing and then invoke using Java reflection the method, which is in another .java file, that loades the application. When done loading, dispose your splash screen.

    After checking the code, you will understand how it works and now customize it your own way.

    Here is some code:

    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    
    /**
     *
     * @author martijn
     */
    public class Splash {
    
        public static void splash() {
            try {
                final BufferedImage img = ImageIO.read(Splash.class.getResourceAsStream("/path/to/your/splash/image/splash.png"));
                JDialog dialog = new JDialog() {
    
                    @Override
                    public void paint(Graphics g) {
                        g.drawImage(img, 0, 0, null);
                    }
                };
                // use the same size as your image
                dialog.setPreferredSize(new Dimension(450, 300)); 
                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                dialog.setUndecorated(true);
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                dialog.repaint();
                try {
                    // Now, we are going to init the look and feel:
    
                    Class uim = Class.forName("javax.swing.UIManager");
                    uim.getDeclaredMethod("setLookAndFeel", String.class).invoke(null, (String) uim.getDeclaredMethod("getSystemLookAndFeelClassName").invoke(null));
    
                    // And now, we are going to invoke our loader method:
                    Class clazz = Class.forName("yourpackage.YourClass");
                    dialog.dispose();
                    // suppose your method is called init and is static
                    clazz.getDeclaredMethod("init").invoke(null);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                dialog.dispose();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }