Splash Screen loading with application

Asked

Viewed 2,338 times

10

My application, when starting, does the first search in the database. How I use the Hibernate, this first connection is a little more time consuming as it assembles the entire bank mapping. I’m thinking of adding a Splash Screen at the beginning, so that the user does not think that the application has locked or is not loading, but by the examples I saw, I must inform an amount of time for the Thread carry. However, the charging time of the system varies according to the settings of the micro, if the system has already been opened on the machine or if it is still in memory.

My question is whether I can make Splash’s lifetime take the loading time of my system.

Below is an example of how I start my system and how I use my Splash.

Splash.java

....

/**
*
*   @author desenvolvimento
*/
public class Splash extends JWindow {

AbsoluteLayout absoluto;
AbsoluteConstraints absimagem, absbarra;
ImageIcon image;
JLabel jLabel;
JProgressBar barra;

public Splash() {

    absoluto = new AbsoluteLayout();
    absimagem = new AbsoluteConstraints(0, 0);
    absbarra = new AbsoluteConstraints(0, 284);
    jLabel = new JLabel();
    image = new ImageIcon(this.getClass().getResource("/imagem/Logo.png"));
    jLabel.setIcon(image);
    barra = new JProgressBar();
    barra.setPreferredSize(new Dimension(285, 10));
    this.getContentPane().setLayout(absoluto);
    this.getContentPane().add(jLabel, absimagem);
    this.getContentPane().add(barra, absbarra);
    this.getContentPane().setBackground(Color.white);

    new Thread() {

        public void run() {

            int i = 0;
            while (i < 101) {
                barra.setValue(i);
                i++;
                try {

                    sleep(150);

                } catch (InterruptedException ex) {
                    Logger.getLogger(Splash.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            TelaLogin x = new TelaLogin();
            x.setVisible(true);

        }

    }.start();
    this.pack();
    this.setVisible(true);
    this.setLocationRelativeTo(null);

}

}

Main java.

public class Agil {


public static void main(String[] args) {
  TelaLogin telaLogin = new TelaLogin();
    telaLogin.validate();
    telaLogin.pack();
    telaLogin.setVisible(false);
   }
}

Telalogin.java

public class TelaLogin extends javax.swing.JFrame {

/**
 * Creates new form TelaLogin
 */
public TelaLogin() {
    initComponents();

   new Splash();

    EmitenteDAO emitentedao = new EmitenteDAO();
    String nomeFantasia = emitentedao.getEmitente();
    LbEmpresaLogin.setText(nomeFantasia);

    LeituraXmlConfig config = new LeituraXmlConfig();

    if (config.getValidaConfig().equals("0")) {

        //Inicia configuração
    } else if (config.getValidaConfig().equals("1")) {

    }


    URL url = this.getClass().getResource("imagem/icon_32.png");
    Image iconeTitulo = Toolkit.getDefaultToolkit().getImage(url);    
    this.setIconImage(iconeTitulo);

    TxUsuarioLogin.setDocument(new EntradaUpperCase());

}

Session session = Session.getSession();

@SuppressWarnings("unchecked")

 ........
  • I think you can take the automatic bar fill out of the thread, and at each load event, it puts a percentage on the bar.

  • Okay, there’s an example where I can base myself?

  • Do a search on the methods wait() and notify();

  • 1

    You’re not using the right resources to work multiple threads in Swing. Read about using Swingworker

3 answers

2


An alternative would be to use the class SplashScreen, with it java itself takes charge of displaying and closing the splash as soon as a window awt/swing is open.

As an example it follows the code I took from the netbeans tutorial and adapted:

public class CustomSplashScreen {

    private static SplashScreen mySplash;
    private static Graphics2D splashGraphics;
    private static Rectangle2D.Double splashProgressArea;

    public static void splashInit() {

        mySplash = SplashScreen.getSplashScreen();

        if (mySplash != null) {
            //pega as dimensoes da imagem que será usada no splashscreen
            // para que a barra fique proporcional
            Dimension ssDim = mySplash.getSize();
            int height = ssDim.height;
            int width = ssDim.width;
            //desenha a área da barra de progresso, você pode alterar as dimensoes pra testar a que mais gostar
            //  os parametros representam posição horizontal  e vertical (em relação a imagem), altura e largura, respectivamente
            splashProgressArea = new Rectangle2D.Double(1.0, height * 0.87, width, height * 0.08);
            //exibe a imagem do splash centralizada na tela
            splashGraphics = mySplash.createGraphics();
            //inicia a barra de progresso(pode ser removido)
            splashProgress(0);
        }
    }

    public static void splashProgress(int pct) {
        if (mySplash != null && mySplash.isVisible()) {
            
            //preenche a area da barra de progresso com a cor informada
            splashGraphics.setPaint(Color.LIGHT_GRAY);
            splashGraphics.fill(splashProgressArea);
            
            //colore bordas na barra de progresso(opcional)
            splashGraphics.setPaint(Color.BLUE);
            splashGraphics.draw(splashProgressArea);
            
            //pega o menor valor das coordenadas(horizontal  X e vertical Y) da barra 
            //será usado para o carregamento(não alterar daqui em diante)
            int x = (int) splashProgressArea.getMinX();
            int y = (int) splashProgressArea.getMinY();
            int wid = (int) splashProgressArea.getWidth();
            int hgt = (int) splashProgressArea.getHeight();
            
            //valor usado para o carregamento da barra
            int doneWidth = Math.round(pct * wid / 100.f);
            doneWidth = Math.max(0, Math.min(doneWidth, wid - 1));
            
            //aqui  é que vai preenchendo o carregamento da barra de acordo com o valor
            //passado em pct    
            splashGraphics.setPaint(Color.GREEN);
            splashGraphics.fillRect(x, y + 1, doneWidth, hgt - 1);
            mySplash.update();
        }
    }
}

But before using the class, it’s important to add an image to your project and the reference in manifest.mf. If you’re using Netbeans, the file will be more or less like this:

Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

Change it this way:

Manifest-Version: 1.0
SplashScreen-Image: <caminho da imagem>
X-COMMENT: Main-Class will be added automatically by build

where caminho da imagem should be the path from where the image is in your project. As an example, see my test project:

inserir a descrição da imagem aqui

Soon, the image address will look like this:

Manifest-Version: 1.0
SplashScreen-Image: splashdemo/splash.png
X-COMMENT: Main-Class will be added automatically by build

Then, to call, just do so in your main

public static void main(String args[]) {

    CustomSplashScreen.splashInit();

    for (int i = 0; i < 10; i++) {
        CustomSplashScreen.splashProgress(i * 20);
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

The for will increment a value that will be passed to progress reference, and (i*20) is just a customization of the way the bar will increase in progress, you can customize here the way you want.

Observing: it is also possible to test by running the netbeans itself by going to the Properties and adding the line -splash:src/splashdemo/splash.png in VM Options:

inserir a descrição da imagem aqui

So it is not necessary to keep generating the jar all the time to test.

There are more examples in https://docs.oracle.com/javase/tutorial/uiswing/misc/splashscreen.html


Limitations

As reported here, progress is not synchronized with Thread loading, but the splash is closed as soon as a awt/swing becomes visible.

0

You must start the Thread Splash, which will appear on your screen immediately at the beginning of the application, and let the second Thread load the bank stops, at the end of the loading of Hibernate, before it calls the application screen, you kill the first thread and here comes the application screen. So it will be "calibrated" for any type of hardware.

0

The Splash Screen was mounted as follows:

The main class calls a Jframe that has an image that is visually in the center of the screen until the application makes the first bank mapping and assembles the communication the screen is visible.

main java.

SplashPrincipal sc = new SplashPrincipal();
    sc.setVisible(true);
    sc.setSize(535, 235);


    TelaLogin telaLogin = new TelaLogin();
    telaLogin.validate();
    telaLogin.pack();
    telaLogin.setVisible(true);

    sc.setVisible(false);
  • Have you ever thought about using the native Splashscreen class of java? it already tries to display for you.

  • never read about it, I will search for information and see if I can improve the function. Thanks for the tip.

  • See the code in this question. http://answall.com/questions/115954/display-splashscreen-progression-enquanto-jframe-%C3%A9-loaded? noredirect=1#comment241883_115954

Browser other questions tagged

You are not signed in. Login or sign up in order to post.