• title: JComboBoxにAnimated GIFを表示する tags: [JComboBox, ImageIcon, ImageObserver, BasicComboPopup, JList] author: aterai pubdate: 2012-03-12T17:23:26+09:00 description: JComboBoxと、そのドロップダウンリストにAnimated GIFを表示します。

概要

JComboBoxと、そのドロップダウンリストにAnimated GIFを表示します。

サンプルコード

private static ImageIcon makeImageIcon(URL url, final JComboBox combo, final int row) {
  ImageIcon icon = new ImageIcon(url);
  //Wastefulness: icon.setImageObserver(combo);
  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) {
      if(combo.isShowing() && (infoflags & (FRAMEBITS|ALLBITS)) != 0) {
        if(combo.getSelectedIndex()==row) {
          combo.repaint();
        }
        BasicComboPopup p = (BasicComboPopup)combo.getAccessibleContext().getAccessibleChild(0);
        JList list = p.getList();
        if(list.isShowing()) {
          list.repaint(list.getCellBounds(row, row));
        }
      }
      return (infoflags & (ALLBITS|ABORT)) == 0;
    };
  });
  return icon;
}
View in GitHub: Java, Kotlin

解説

  • JComboBox自体が非表示(JComboBox#isShowing(...)==false)の場合は、再描画しない
  • Animated GIFが選択されている(JComboBox#getSelectedIndex()==row)場合のみ、JComboBox#repaint()で再描画する
  • ドロップダウンリストが表示されている場合、Animated GIFの表示されている領域(JList#getCellBounds(row, row)で取得)だけ再描画

参考リンク

コメント