为啥 JTable 列中没有显示动画 .gif 图标?

Posted

技术标签:

【中文标题】为啥 JTable 列中没有显示动画 .gif 图标?【英文标题】:Why is an animated .gif icon not showing in JTable column?为什么 JTable 列中没有显示动画 .gif 图标? 【发布时间】:2015-07-03 11:30:16 【问题描述】:

这是处理中的.gif

这里是initial.png

这是输出

这里是代码。 processing.gif 正在其他位置工作,例如在JTabbedPane 的选项卡中。在JTable 的列中,它没有显示。有什么解释和解决办法吗? processing.gif 是一个移动图标,表示正在加载某些内容。

import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JFrame

    public TableIcon()
    
        ImageIcon initial = new ImageIcon(getClass().getResource("initial.png"));
        ImageIcon processing = new ImageIcon(getClass().getResource("processing.gif"));


        String[] columnNames = "Picture", "Description";
        Object[][] data =
        
            initial, "initial",
            processing, "processing"
        ;

        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable( model )
        
            public Class getColumnClass(int column)
            
                return getValueAt(0, column).getClass();
            
        ;
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    

    public static void main(String[] args)
    
        TableIcon frame = new TableIcon();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    


【问题讨论】:

当然,正如我所说,它在 JTabbedPane 中工作 intial.png 正在显示,它与 processing.gif 位于同一位置。这不是这里的问题。我很困惑为什么不能在 JTable 中显示移动的 .gif 附上图片 你可以下载上图试试 【参考方案1】:

默认情况下,动画 gif 在 JTable 中效果不佳。但是有一个简单的方法可以解决这个问题,使用 AnimatedIcon 可以找到的类 here

基本上,它重新实现了Icon接口,注册了你渲染图标的位置,当需要绘制新的gif帧时,它会自动重新绘制正确的区域。

here 提供了另一种替代方法,您可以在其中为每个需要渲染动画 gif 的单元格注册一个特定的 ImageObserver,但我觉得它有点乏味。

【讨论】:

【参考方案2】:

如果JTable 完全支持动画 GIF,那就太好了,但不幸的是,它看起来不像。您已经提到它确实在JTabbedPane 的选项卡中工作。我在 TableIcon 构造函数的末尾添加了以下行:

getContentPane().add(new JLabel(processing), BorderLayout.SOUTH);

这稍微改变了情况:表格显示了 GIF 的一帧,而不是什么都没有。动画 GIF 正在标签中工作。我还注意到,当您调整窗口大小时,表格中的动画正在运行。这给了我这个肮脏黑客的想法,它似乎在我的系统上工作(也添加到 TableIcon 构造函数的末尾):

final Timer animationTimer = new Timer(100, e -> table.repaint());
animationTimer.start();

【讨论】:

以上是关于为啥 JTable 列中没有显示动画 .gif 图标?的主要内容,如果未能解决你的问题,请参考以下文章

如何:在第一列中具有可折叠 JTree 并在其他列中具有数据的 JTable?

android 怎样显示gif动画

如何在Canvas上显示gif动画 SWT

ImageView:动画 gif 预览

如何在wps文档里面显示gif动画?

R语言gganimate包创建可视化gif动图可视化动图:gganimate包创建动态线型图动画基于transition_time函数使用geom_point函数显示动画移动的数据点