JWindowを使ったSplash Screenの表示

編集者:Terai Atsuhiro
作成日:2003-09-25
更新日:2024-02-02 (金) 11:52:27

概要

JWindowを使って、Splash Screenを表示します。起動画面とか、Splash Windowなどといった呼び方もあるようです。 以下のサンプルコードは、%JAVA_HOME%/demo/jfc/SwingSet2/src/SwingSet2.java から引用改変したものです。

サンプルコード

private JWindow splashScreen;
private JLabel  splashLabel;
public void createSplashScreen(String path) {
  ImageIcon img = new ImageIcon(getClass().getResource(path));
  splashLabel  = new JLabel(img);
  splashScreen = new JWindow(getFrame());
  splashScreen.getContentPane().add(splashLabel);
  splashScreen.pack();
  splashScreen.setLocationRelativeTo(null);
}
public void showSplashScreen() {
  splashScreen.show();
}
public void hideSplash() {
  splashScreen.setVisible(false);
  splashScreen = null;
  splashLabel  = null;
}
//コンストラクタ
public HogeHoge() {
  createSplashScreen("/resources/images/splash.png");
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      showSplashScreen();
    }
  });
  //initializePanel();
  //といった初期化などの重い処理の代わりに、このサンプルではsleep
  try{
    Thread.sleep(3000);
  }catch(InterruptedException e) {
  	 System.out.println(e);
  }
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      showPanel();
      hideSplash();
    }
  });
}

解説

スプラッシュ・スクリーンの画像は事前に用意しておいてください。上記のサンプルコードでは、クラスパスの通った場所にある /resources/images/splash.png を読み込んで表示するようになっています。

サンプルの画像は、n-Genを使って生成しています。

あとはSwingUtilities.invokeLater()を使用すれば簡単です。

コメント