• category: swing folder: SplashScreen title: JWindowを使ったSplash Screenの表示 tags: [JWindow, JLabel] author: aterai pubdate: 2003-10-13T06:25:21+09:00 description: JWindowを使って、Splash Screenを表示します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTTtxuiuuI/AAAAAAAAAk4/JhuyuS80C4M/s800/SplashScreen.png

概要

JWindowを使って、Splash Screenを表示します。以下のサンプルコードは、%JAVA_HOME%/demo/jfc/SwingSet2/src/SwingSet2.javaから引用改変したものです。

サンプルコード

private JWindow splashScreen;
private JLabel  splashLabel;
public MainPanel() {
  super();
  createSplashScreen(SPLASH_PATH);
  EventQueue.invokeLater(new Runnable() {
    @Override public void run() {
      showSplashScreen();
    }
  });
  //長い処理のdummy
  try {
    Thread.sleep(3000);
  } catch (InterruptedException e) {
    System.out.println(e);
  }
  EventQueue.invokeLater(new Runnable() {
    @Override public void run() {
      showPanel();
      hideSplash();
    }
  });
}
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.setVisible(true);
}
public void hideSplash() {
  splashScreen.setVisible(false);
  splashScreen = null;
  splashLabel  = null;
}
public JFrame getFrame() {
  return frame;
}
public void showPanel() {
  this.setPreferredSize(new Dimension(300, 200));
  frame.getContentPane().add(this);
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  frame.pack();
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
}
View in GitHub: Java, Kotlin

解説

上記のサンプルコードでは、クラスパスの通った場所にある/resources/images/splash.pngを読み込んでスプラッシュ・スクリーン(起動画面)を表示しています。JWindowの表示、非表示は、イベントディスパッチスレッド(EDT)で行われるように、Runnableを作成しEventQueue.invokeLater()メソッドで実行しています。


Java SE 6では、起動時にスプラッシュ・スクリーンとして表示する画像をコマンドラインやmanifest.mfで指定したり、SplashScreenオブジェクトを生成して表示することができます。

参考リンク

コメント