Image as splashscreen for JavaFX application not hiding automatically

∥☆過路亽.° 提交于 2021-01-28 02:49:25

问题


I have a simple .png image file that I wish to show while the JavaFX application is loading.

I am using NetBeans as my IDE and I know that splashscreen can be added like so: Project properties -> Run -> VM Options: -splash:path-to-image

Now the splashscreen starts nicely, but it won't close after my application has started. Just sits there on the screen until I close my application completely. As the documentation says (http://docs.oracle.com/javase/7/docs/api/java/awt/SplashScreen.html) "The splash screen window is closed automatically as soon as the first window is displayed by Swing/AWT". JavaFX is not Swing nor AWT application. So how can I close it?

Any help is appreciated!


回答1:


Ok, answering my own question.

When splash is set in VM Options: -splash:path-to-image. The in JavaFX I was able to close it like this:

//Get the splashscreen
final SplashScreen splash = SplashScreen.getSplashScreen();

//Close splashscreen
    if (splash != null) {
        System.out.println("Closing splashscreen...");
        splash.close();
    }

Hope this is somewhat helpful to others also! ;)




回答2:


On AdoptOpenJDK 14, calling SplashScreen.getSplashScreen() throws a HeadlessException.

To work around this, I did:

    System.setProperty("java.awt.headless", "false");
    Optional.ofNullable(SplashScreen.getSplashScreen()).ifPresent(SplashScreen::close);
    System.setProperty("java.awt.headless", "true");



回答3:


While the accepted answer is correct, there is room to improve this a little bit. You shouldn't use the final keyword as this would make the splash image hang. In addition, instead of using the null, you can check whether the splash is visible by using the built in isVisible() method.

import java.awt.*;

public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        SplashScreen splash = SplashScreen.getSplashScreen();

        if (splash.isVisible()) {
            System.out.println("Is visible");

            splash.close();
        }
    }
}


来源:https://stackoverflow.com/questions/29451590/image-as-splashscreen-for-javafx-application-not-hiding-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!