我正在尝试在 JComboBox 中使用动画 (GIF) 图标。
由于 DefaultListCellRenderer 是基于 JLabel 的,所以在将 ImageIcon 放入 ComboBoxModel 时直接支持它们。
但是,这不适用于动画 GIF。
在下拉列表中,除非它们被选中,否则它们根本不会显示(尽管 GIF 在常规 JLabel 中使用时确实有效)
填充组合框的代码很简单:
ImageIcon[] data = new ImageIcon[4];
data[0] = new ImageIcon("icon_one.gif");
data[1] = new ImageIcon("icon_two.gif");
data[2] = new ImageIcon("icon_three.gif");
data[3] = new ImageIcon("icon_four.gif");
ComboBoxModel model = new DefaultComboBoxModel(data);
setModel(model);
icon_one.gif 是静态的,显示没有任何问题。其他都是动画的。(图像已正确加载,因为如果我将这些图标中的任何一个直接分配给 JLabel,它们就会显示得很好)
我还尝试使用我自己的基于 JPanel 的 ListCellRenderer (灵感来自这个问题的答案:Java animated GIF without using a JLabel)。
这工作得更好一点,但也不理想。仅当我在显示下拉菜单时将鼠标移到它们上方时才会显示这些图标。所以我想这是一个修复问题,虽然我不知道在哪里
这是我的 JPanel 中实现 ListCellRenderer 接口的部分。
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
this.image = ((ImageIcon)value).getImage();
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
revalidate();
repaint();
return this;
}
调用 revalidate() 和 repaint() 的灵感来自于查看 JLabel.setIcon() 的代码
paint() 方法也很简单:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
g.drawImage(image, 0, 0, this);
}
}
有任何想法吗?我真的不需要在下拉菜单中对这些图标进行动画处理(尽管那会很好),但我至少希望看到静态图像。