• title: ImageIconのリソースを開放してAnimatedGifを最初から再生する tags: [ImageIcon, Animation, JButton, JLabel] author: aterai pubdate: 2013-08-19T00:06:01+09:00 description: JButtonなどのコンポーネントに設定したAnimatedGifのリソースを一旦解放して最初から再生します。

概要

JButtonなどのコンポーネントに設定したAnimatedGifのリソースを一旦解放して最初から再生します。java - Animated ImageIcon as Button - Stack Overflowを参考にしています。

サンプルコード

final ImageIcon animatedIcon = new ImageIcon(url);
JButton button = new JButton(icon9) {
  @Override protected void fireStateChanged() {
    ButtonModel m = getModel();
    if (isRolloverEnabled() && m.isRollover()) {
      animatedIcon.getImage().flush();
    }
    super.fireStateChanged();
  };
};
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、Image#flush()メソッドを使用してImageオブジェクトのリソースを解放することで、Animated GIF画像のアニメーションを初期状態までリセットしています。

  • 左: JButton
    • JButton#setRolloverIcon(...)Animated GIFを設定し、マウスのロールオーバーでImage#flush()され、カウントダウンアニメーションが最初からスタート
    • JButton#setIcon(...)には先頭画像のアイコン、JButton#setPressedIcon(...)には、空アイコンを設定
  • 右: JLabel
    • マウスリスナーを追加し、クリックでImage#flush()が呼ばれて、アニメーションが再開
    • JButtonで、Image#flush()されると、同じImageオブジェクトを使用しているのでアニメーションが止まる

参考リンク

コメント