图像未显示在Java Swing GUI JFrame中

时间:2018-03-17 01:36:17

标签: java swing user-interface jframe

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

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 个答案:

答案 0 :(得分:3)

您正在使用Thread.sleep(),因此GUI会休眠并且无法重新绘制自身。有关详细信息,请阅读Concurrency上的Swing教程中的部分。

不要使用Thread.sleep()。

而是使用Swing Timer在5秒内安排活动。有关详细信息,请阅读How to Use Timers上的Swing教程中的部分。

答案 1 :(得分:1)

像camickr所说,Swing Timer将是解决这个问题的正确方法。但是,由于创建自定义线程是您将来会做的很多事情,所以这里有一个"手册"如何解决这个问题的例子:

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.
}