如何在DefaultTableModel中插入一行图像?

时间:2018-04-18 08:07:39

标签: java image swing jtable

enter image description here

public static void table2() {
    Object num[] = new Object[1];
    for (int q = 0; q < MyDto.userList.size(); q++) {
        try {

            //ImageIcon i2 = new ImageIcon(new ImageIcon(MyDto.userList.get(q).getMyImg()).getImage()
            //      .getScaledInstance(150, 120, Image.SCALE_SMOOTH));

             ImageIcon i2 = new ImageIcon("/Users/junseok/Desktop/1.png");
            JLabel lbImage1 = new JLabel(i2);
            lbImage1.setIcon(i2);
            num[0] = lbImage1;
            model2.addRow(num);
            System.out.println(num[0].toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

为什么不显示图像?为什么只写toString()??

1 个答案:

答案 0 :(得分:0)

  

为什么只写toString()??

默认渲染器只调用TableModel中对象的toString()方法。

  

为什么不显示图像?

您需要向TableModel(而不是JLabel)添加Icon。然后你需要告诉表格Icon存储在列中,以便表格可以选择适当的渲染器来绘制图标。

这是通过覆盖TableModel的getColumnClass(...)方法完成的:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JPanel
{
    public TableIcon()
    {
        Icon aboutIcon = new ImageIcon("about16.gif");
        Icon addIcon = new ImageIcon("add16.gif");
        Icon copyIcon = new ImageIcon("copy16.gif");

        String[] columnNames = {"Picture", "Description"};
        Object[][] data =
        {
            {aboutIcon, "About"},
            {addIcon, "Add"},
            {copyIcon, "Copy"},
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            @Override
            public Class getColumnClass(int column)
            {
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Table Icon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableIcon());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

}