---
category: swing
folder: AnimatedIconInTableCell
title: JTableのセルにAnimated GIFを表示する
tags: [JTable, ImageIcon, ImageObserver, Animation]
author: aterai
pubdate: 2012-03-05T01:22:05+09:00
description: ImageIconにImageObserverを設定して、JTableのセル中でAnimated GIFのアニメーションを行います。
image: https://lh3.googleusercontent.com/-138Snht85-E/T1B6iHoG1pI/AAAAAAAABJw/XaESowuWEC4/s800/AnimatedIconInTableCell.png
---
* 概要 [#summary]
`ImageIcon`に`ImageObserver`を設定して、`JTable`のセル中で`Animated GIF`のアニメーションを行います。

#download(https://lh3.googleusercontent.com/-138Snht85-E/T1B6iHoG1pI/AAAAAAAABJw/XaESowuWEC4/s800/AnimatedIconInTableCell.png)

* サンプルコード [#sourcecode]
#code(link){{
ImageIcon icon = new ImageIcon(url);
//Wastefulness: icon.setImageObserver((ImageObserver) table);
icon.setImageObserver(new ImageObserver() {
  //@see http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
  @Override public boolean imageUpdate(
      Image img, int infoflags, int x, int y, int w, int h) {
    //@see javax.swing.JLabel#imageUpdate(...)
    if (!table.isShowing()) {
      return false;
    }
    //@see java.awt.Component#imageUpdate(...)
    if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {
      int vr = table.convertRowIndexToView(row); //JDK 1.6.0
      int vc = table.convertColumnIndexToView(col);
      table.repaint(table.getCellRect(vr, vc, false));
    }
    return (infoflags & (ALLBITS | ABORT)) == 0;
  };
});
}}

* 解説 [#explanation]
上記のサンプルでは、[http://www2.gol.com/users/tame/swing/examples/SwingExamples.html AnimatedIconTableExample.java]を参考にして、`Animated GIF`ファイルから作成した`ImageIcon`に、`setImageObserver(ImageObserver)`を設定しています。直接`JTable`を`ImageObserver`として設定するとすべてのセルが再描画されて無駄なので、`JTable#getCellRect(row, col, false)`で対象セルのみ`repaint`するようにしています。

- [http://www2.gol.com/users/tame/swing/examples/SwingExamples.html AnimatedIconTableExample.java]からの変更点
-- `JTable#isShowing(...)==false`で、非表示の場合は`JTable#repaint(...)`しない
-- `JDK 1.6.0`以降に導入された[https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTable.html#convertRowIndexToView-int- JTable#convertRowIndexToView(row)]メソッドを使用し、行がソートされていても正しいセルのみを再描画する
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTable.html#convertColumnIndexToView-int- JTable#convertColumnIndexToView(col)]メソッドを使って、列の入れ替えがあっても正しいセルのみを再描画する

* 参考リンク [#reference]
- [http://www2.gol.com/users/tame/swing/examples/SwingExamples.html AnimatedIconTableExample.java]
-- 元サイトには繋がらないので、[https://www.google.com/search?q=AnimatedIconTableExample.java animatedicontableexample.java - Google 検索]などのミラーを参考
- [[JTreeのTreeNodeにAnimated GIFを表示する>Swing/AnimatedTreeNode]]

* コメント [#comment]
#comment
#comment