代码之家  ›  专栏  ›  技术社区  ›  Ian Campbell

如何在不引发NullPointerException的情况下使用SplashScreen?

  •  0
  • Ian Campbell  · 技术社区  · 13 年前


    无论我尝试什么, SplashScreen.getSplashScreen() 总是 null .

    从网上搜索中,我发现这是一个常见的问题,这与不提供 SplashScreen 要使用的图像。。。因此,在浏览这些方法时,我觉得 setImageURL(URL) 应该使用。这仍然不起作用。

    SO上也有类似的问题,例如 this ,这些都没有帮助,似乎建议使用无数的插件或从头开始创建这样一个类 Frame 。甚至 Oracle tutorial 是神秘的,并且没有概述使用中的每个逻辑步骤 启动屏幕 正确地

    如果不可能或不必要地难以使用 启动屏幕 ,除了这样做还有其他选择吗?或者有人想出了解决这个问题的简单方法吗?


    这是我的尝试:
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.SplashScreen;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.net.URL;
    
    /**
     */
    public final class MainGUI implements ActionListener {
    
        /**
         * @throws IOException 
         * @throws IllegalStateException 
         * @throws NullPointerException 
         */
        private final static void showSplashScreen() throws NullPointerException, IllegalStateException, IOException {
            final SplashScreen splash = SplashScreen.getSplashScreen();
            Graphics2D graphics = splash.createGraphics();
    
            // adding image here:
            URL imageSource = new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Space_Shuttle_Atlantis_approaching_the_Kennedy_Space_Center_to_land_following_STS-122.jpg/800px-Space_Shuttle_Atlantis_approaching_the_Kennedy_Space_Center_to_land_following_STS-122.jpg");
            splash.setImageURL(imageSource);
    
            // coordinates and dimensions:
            int x = 100, y = x;
            int width = 500, height = width;
    
            // (x, y), width, height:
            graphics.create(x, y, width, height);
    
            graphics.setBackground(Color.BLUE);
    
            // adding and centering the text:
            graphics.drawString("centered text", (x + width)/2, (y + height)/2);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            try {
                showSplashScreen();
            } catch (NullPointerException | IllegalStateException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } // end of MainGUI
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   MadProgrammer    13 年前

    看看 How to Create a Splash Screen

    您需要通过命令行或Jar清单提供图像

    更新一些基础知识

    您必须为启动屏幕提供一个图像。如果不提供,它将始终为null。

    有两种方法可以做到这一点

    1.从命令行

    java -splash:path/to/image.jpg {other command line options}
    

    图像必须位于应用程序的类加载器的上下文中(例如嵌入式资源)。

    2.清单文件

    这有点困难,但会导致更简单的执行(因为没有人需要记住添加命令行;)。。。

    退房 Working with Manifest Files 了解更多详细信息。

    你如何创建它取决于你的环境。

    例如,在Netbeans中,可以在项目属性对话框中的 Application 节点。