Java Swing How to - Add an animated GIF to JComboBox








Question

We would like to know how to add an animated GIF to JComboBox.

Answer

//Code revised from /* ww  w .ja  v a  2s .c o m*/
//http://stackoverflow.com/questions/9555281/using-an-animated-gif-in-a-jcombobox
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.net.URL;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboPopup;

public class Main {


  public static void main(String[] args) {
    JComboBox<Object> combo = new JComboBox<>();
    URL url = new Main().getClass().getResource("animated.gif");
    combo.setModel(new DefaultComboBoxModel(new Object[] {
        makeImageIcon(url, combo, 0) }));

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(combo);
    f.setSize(320, 240);
    f.setVisible(true);
  }
  static ImageIcon makeImageIcon(URL url, JComboBox combo,int row) {
    ImageIcon icon = new ImageIcon(url);
    icon.setImageObserver(new ImageObserver() {
      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;
  }
}