问题



Here is the code. processing.gif is working in other locations such as in the tab of a JTabbedPane
. Here in the column of a JTable
, it is not showing. Any explanation and solution? processing.gif is a moving icon that indicates that something is loading.
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);
}
}
回答1:
Animated gif's don't work well by default in JTable. But there is an easy way to fix this, use the AnimatedIcon
class that can be found here
Basically, it reimplements Icon
interface, register where you rendered the icon, and when a new frame of the gif needs to be painted, it will automatically repaint the correct area.
There is another alternative provided here where you register a specific ImageObserver for each cell that needs to render an animated gif, but I find it a bit more tedious.
回答2:
It would be great if animated GIFs would be fully supported in a JTable
, but it unfortunately does not look like it. You already mentioned that it does work in the tab of a JTabbedPane
. I added the following line to the end of the TableIcon
constructor:
getContentPane().add(new JLabel(processing), BorderLayout.SOUTH);
This changed the situation slightly: the table shows one frame of the GIF instead of nothing. The animated GIF is working in the label. I also noticed that when you resize the window, the animation in the table is running. This gave me the idea for this dirty hack, which seems to work on my system (also added to the end of the TableIcon
constructor):
final Timer animationTimer = new Timer(100, e -> table.repaint());
animationTimer.start();
来源:https://stackoverflow.com/questions/29854629/why-is-an-animated-gif-icon-not-showing-in-jtable-column