自定义 Java 启动画面“冻结"直到整个应用程序加载完毕 [英] Custom Java splash screen "freezes" until the whole application has loaded

查看:31
本文介绍了自定义 Java 启动画面“冻结"直到整个应用程序加载完毕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,需要很长时间才能加载.因此,我想开发一个启动画面,可以向用户提供有关正在加载的内容的反馈.一个带有图像、标签和 JProgressBar 的简单 JFrame.

I have a program, that takes a long time to load. Because of this, I wanted to develop a splash screen that can provide feedback to the user on what is being loaded. A simple JFrame with an image, label and JProgressBar.

我一直在试验,最好的结果是在我的 main() 中这样做:

I have been experimenting and the best results I've had are doing this in my main():

SwingUtilities.invokeAndWait(new Runnable() {

    public void run() {

        new SplashScreen();
    }
});

SwingUtilities.invokeAndWait(new Runnable() {

    public void run() {

        //Code to start system
        new MainFrame();
        //.. etc
    }
});

SplashScreen 和 MainFrame 都是扩展 JFrame 的类.我也在使用 Substance 作为库.

Both SplashScreen and MainFrame are classes extending JFrame. I am also using Substance as a Library.

SplashScreen 的构造函数向自身添加 JLabel 和 JProgressBar,打包并设置可见.JProgressBar 是 setIndeterminate(true);

SplashScreen's constructor adds a JLabel and JProgressBar to itself, packs and sets visible. The JProgressBar is setIndeterminate(true);

当我运行我的程序时,我的 SplashScreen 会显示,但 ProgressBar 被锁定,它不会移动,直到程序的其余部分启动它才会按预期开始移动.

When I run my program, my SplashScreen is displayed but the ProgressBar is locked, it doesn't move, not until the rest of the program has started does it start moving as expected.

我在这里错过了什么?我所做的所有搜索似乎都没有提到这个问题,而且大多数自定义启动画面"的实现方式与我自己非常相似.

What am I missing here? All searching I've done doesn't seem to mention this problem and most "custom splash screen" implementations go about it a very similar way to myself.

推荐答案

其他答案已经涵盖了大部分内容,但简而言之,您的问题是您正在 Swing 事件调度线程中运行启动系统的代码".所有与 GUI 相关的代码(包括组件创建)必须在 EDT 上运行,但所有其他代码不应在 EDT 上运行.尝试更改您的程序以执行此操作:

Other answers have covered most of this but in brief your problem is that you are running the "Code to start system" in the Swing event dispatch thread. All GUI-related code (including component creation) must be run on the EDT but all other code should not be run on the EDT. Try changing your program to do this:

SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
        new SplashScreen();
    }
});
// Code to start system (nothing that touches the GUI)
SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
        new MainFrame();
    }
});
//.. etc

这篇关于自定义 Java 启动画面“冻结"直到整个应用程序加载完毕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆