如何将图像插入到JTable单元格中

有人能指出我正确的方向如何将图像添加到Java表格单元格。

JTable已经为图标提供了一个默认的渲染器。 你只需要告诉表什么数据存储在给定的列,所以它可以select适当的渲染器。 这是通过覆盖getColumnClass(…)方法来完成的:

import java.awt.*; import javax.swing.*; import javax.swing.table.*; public class TableIcon extends JFrame { public TableIcon() { ImageIcon aboutIcon = new ImageIcon("about16.gif"); ImageIcon addIcon = new ImageIcon("add16.gif"); ImageIcon copyIcon = new ImageIcon("copy16.gif"); String[] columnNames = {"Picture", "Description"}; Object[][] data = { {aboutIcon, "About"}, {addIcon, "Add"}, {copyIcon, "Copy"}, }; DefaultTableModel model = new DefaultTableModel(data, columnNames); JTable table = new JTable( model ) { // Returning the Class of each column will allow different // renderers to be used based on Class 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); } } 

要么在前面创buildimageicon:

 ImageIcon icon = new ImageIcon("image.gif"); table.setValueAt(icon, row, column); 

或者您可以尝试覆盖您的图标字段的渲染器:

 static class IconRenderer extends DefaultTableCellRenderer { public IconRenderer() { super(); } public void setValue(Object value) { if (value == null) { setText(""); } else { setIcon(value); } }