javaswingsplash-screenevent-dispatch-threadjprogressbar

How to call a class with JProgressBar first & then run the main program?


I have created a separate class which displays a splash screen containing Progress Bar and I have a separate class where my main program starts from. When the program is started I want the Progress bar to execute first and then after it closes, I want my Main program to start.

This is my code for the Splash Screen with Progress Bar

package MISC;

import javax.swing.*;
import java.awt.*;

public class SplashScreen extends JFrame {

    JLabel label;
    JProgressBar jProgessionBar;

    public SplashScreen() {

        label = new JLabel("Loading...");
        label.setBounds(210, 210, 100, 30);
        add(label);

        jProgessionBar = new JProgressBar(0, 100); //Length of progression bar
        jProgessionBar.setBounds(140, 250, 200, 25);
        jProgessionBar.setValue(0);
        jProgessionBar.setStringPainted(true);
        add(jProgessionBar);
        setSize(500,450);
        setLocation(500,200);
        setLayout(null);
    }

        public void load(){
            int i;
            try {
                for (i = 0; i < 100; i++) {
                    Thread.sleep(35);
                    jProgessionBar.setValue(i);
                }
                if (i == 100) {
                    new Main();
                    dispose();
                }
            } catch (Exception e) {
                System.out.println("Splash Screen Error");
            }
    }

    public static void main(String[] args) {

        SplashScreen f = new SplashScreen();
        f.setVisible(true);
        f.load();
        f.setResizable(false);
    }
}

Solution

  • Using javax.swing.Timer would be the preferred way to do this

    class Example implements ActionListener {
      Timer t = new Timer(this, 35);
      JProgressBar jProgressBar = ...;
      private int i = 0;
      public void start() {
        t.start();
      }
    
      public void actionPerformed(ActionEvent ae) {
         i++;
         jProgessionBar.setValue(i);
         if (i == 100) {
           new Main();
           t.cancel();
         }
      }