【问题标题】:How to write a splash screen?如何编写启动画面?
【发布时间】:2013-03-03 14:22:02
【问题描述】:

我正在使用 Java 制作游戏。

目前,我有几节课。重要的是:

  • LevelBuilder 类在调用默认构造函数时将创建一个包含所需组件的 jframe,然后运行一个 gameloop 线程,该线程将使用后缓冲区更新甚至 1/20 秒。
  • 另一个类是 MainMenu 类,我希望在其中包含 main 方法并在 JFrame 中显示我的徽标。

最后我想让 MainMenu 为 JFrame 绘制一个启动画面,然后在 5 秒后 LevelBuilder 在原始 JFrame 内绘制,而不创建新的。

对不起,如果这是一个基本问题,我刚开始学习 Java。

【问题讨论】:

  • 请发布相关代码,而不是简单的解释它的文本。

标签: java swing jframe


【解决方案1】:

可以通过清单简单地将启动画面添加到您的 jar 中。

问题是默认情况下它只会在 Swing 应用程序加载时才显示。因此,第 2 次(第 3 次、第 4 次等)执行会快速显示闪屏,因为 JVM 和 GUI 使用的类等已被加载。

在我的游戏中,我使用了以下两种方法来创建停留时间更长的飞溅:

/**
 * This will render the splash for longer than just loading components
 *
 * @return true if there is a splash screen file supplied (set via java or
 * manifest) or false if not
 * @throws IllegalStateException
 */
private boolean showSplash() throws IllegalStateException {
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash == null) {
        return false;
    }
    Graphics2D g = splash.createGraphics();
    if (g == null) {
        return false;
    }
    for (int i = 0; i < 100; i++) {//loop 100 times and sleep 50 thus 100x50=5000milis=5seconds
        renderSplashFrame(g);
        splash.update();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
    }
    splash.close();
    return true;
}

private void renderSplashFrame(Graphics2D g2d) {
    //draw anyhting else here
}

这将被称为:

JFrame frame=...;

 ...

//show splash
if (!showSplash()) {
     JOptionPane.showMessageDialog(null, "SplashScreen could not be shown!", "Splash Error: 0x003", JOptionPane.ERROR_MESSAGE);
 }

// set JFrame visible
frame.setVisible(true);
frame.toFront();

请注意,showSplash() 表示如果没有提供启动画面,即您没有在清单中添加一个,它将返回 false。

如果您还没有阅读过How to Create a Splash Screen,我也建议您阅读。

另请参阅其他类似的答案/问题:Make splash screen with progress bar like Eclipse

【讨论】:

    猜你喜欢
    • 2010-10-16
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多