I\'m trying to use animated (GIF) icons in a JComboBox.
As the DefaultListCellRenderer is based on JLabel, ImageIcons are directly supported when putting them into t
This example was inspired from AnimatedIconTableExample.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
class MainPanel {
public JComponent makeUI() {
JComboBox combo = new JComboBox();
URL url1 = getClass().getResource("static.png");
URL url2 = getClass().getResource("animated.gif");
combo.setModel(new DefaultComboBoxModel(new Object[] {
new ImageIcon(url1), makeImageIcon(url2, combo, 1)
}));
JPanel p = new JPanel();
p.add(combo);
return p;
}
private static ImageIcon makeImageIcon(
URL url, final JComboBox combo, final int row) {
ImageIcon icon = new ImageIcon(url);
icon.setImageObserver(new ImageObserver() {
//http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
//AnimatedIconTableExample.java
@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;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new MainPanel().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}