如何将图像插入Jtable(自定义代码)

时间:2013-12-17 15:43:19

标签: java swing jtable

当我尝试在JTable中插入生成的netbeans时遇到了很多困难。

捕获我的JTable的自定义代码。

enter image description here

所以我如何准确地将Image设置为我的类代码中的jtable。

1 个答案:

答案 0 :(得分:3)

您需要覆盖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 (column == 0) ? Icon.class : Object.class;
            }
        };
        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);
    }

}