0

我编写了一个 JWindow,用作我的桌面应用程序的启动屏幕。我遇到的问题是,在窗口变得可见后,在显示预期图像之前它暂时是空白的。空白窗口有时会保持在 0.5 秒到 2 秒之间。我希望在窗口可见之前完全呈现内容。

我在使用 Java 1.6 的 MacOS 上。

这是我启动后立即出现的窗口:

在此处输入图像描述

仅仅半秒后,它就显示了图像。图像非常小(大约 95kBytes JPG)。我知道问题不在于 ImageIcon 加载,因为构造函数应该在加载图像之前阻塞。

在此处输入图像描述

这是我的代码:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JWindow;

public class SplashScreen extends JWindow
{
    public SplashScreen()
    {
        ClassLoader classLoader = this.getClass().getClassLoader();
        ImageIcon imageIcon = new ImageIcon(classLoader.getResource("res/landscape.jpg"));
        while (imageIcon.getImageLoadStatus() != MediaTracker.COMPLETE) {}
        JLabel lbl = new JLabel(imageIcon);
        getContentPane().add(lbl, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(null);

        MouseListener mouseListener = new MouseAdapter()
        {
            public void mousePressed(MouseEvent event)
            {
                setVisible(false);
                dispose();
            }
        };

        addMouseListener(mouseListener);
        setVisible(true);
    }

    public static void main(String argv[])
    {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SplashScreen ss = new SplashScreen();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

编辑:在循环中添加了 imageIcon.getImageLoadStatus() ,但没有效果。

4

2 回答 2

1

尝试使用 JDK SplashScreen。图像立即为我加载。

请参阅如何创建启动画面

于 2014-03-03T19:15:33.637 回答
0

当您构建 ImageIcon 时,您并没有通过阻塞操作将图像完全加载到内存中,您的 ClassLoader.getResource 只会返回一个 URL。阅读ImageIcon 的构造函数详细信息,它说它开始加载 URL,但不会阻塞。您可以通过imageIcon.getImageLoadStatus()方法检查图像何时完成加载。当返回完成时,也许然后设置 window.setVisible(true)。

于 2014-03-03T18:56:04.187 回答