代码之家  ›  专栏  ›  技术社区  ›  TheShield

Java Swing GUI JFrame中未显示图像

  •  0
  • TheShield  · 技术社区  · 6 年前

    我有一个调用此函数的主函数:

    private void splashScreen() throws MalformedURLException {
        JWindow window = new JWindow();
        ImageIcon image = new ImageIcon(new URL("https://i.imgur.com/Wt9kOSU.png"));
        JLabel imageLabel = new JLabel(image); 
        window.add(imageLabel);
        window.pack();
        window.setVisible(true);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        window.setVisible(false);
        window.dispose();
    }
    

    我已将图像添加到窗口,打包窗口,然后使其可见,框架弹出,但图像未显示在框架中。我很确定这个代码应该可以工作?

    2 回复  |  直到 6 年前
        1
  •  3
  •   camickr    6 年前

    您正在使用线程。sleep()使GUI休眠,无法重新绘制自身。阅读Swing教程中的部分 Concurrency 了解更多信息。

    不要使用线程。睡眠()。

    而是使用 Swing Timer 将事件安排在5秒内。阅读Swing教程中的部分 How to Use Timers 了解更多信息。

        2
  •  1
  •   Dreamspace President    6 年前

    正如camickr所说,摆动计时器是解决这一问题的正确方法。但是,由于创建自定义线程是您将来要做的很多事情,下面是一个“手动”示例,介绍如何解决此问题:

    private void showSplashScreen() {
    
        [Create window with everything and setVisible, then do this:]
    
        final Runnable threadCode = () -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SwingUtilities.invokeLater(window::dispose); // Closes the window - but does so on the Swing thread, where it needs to happen.
            // The thread has now run all its code and will die gracefully. Forget about it, it basically never existed.
            // Btw., for the thread to be able to access the window like it does, the window variable either needs to be "final" (((That's what you should do. My mantra is, make EVERY variable (ESPECIALLY method parameters!) final, except if you need them changeable.))), or it needs to be on class level instead of method level.
        };
    
        final Thread winDisposerThread = new Thread(threadCode);
        winDisposerThread.setDaemon(true);  // Makes sure that if your application dies, the thread does not linger.
        winDisposerThread.setName("splash window closer timer"); // Always set a name for debugging.
        winDisposerThread.start(); // Runs the timer thread. (Don't accidentally call .run() instead!)
        // Execution of your program continues here IMMEDIATELY, while the thread has now started and is sleeping for 5 seconds.
    }