JTable显示图片

显示的效果:

JTable显示图片

 

代码:

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.io.File;
import java.util.Vector;

/**
 * Created with IntelliJ IDEA.
 * User: luckystar2008
 * Date: 13-6-18
 * Time: 下午1:56
 * To change this template use File | Settings | File Templates.
 */
public class IconAndTextTable extends JFrame{
    private JTable  table = null;
    String filePath = "D:\\luckystar2008\\works\\QDII\\SR\\副本投资核算系统科目(含外币)__2013_06_17.xlsx";

    public void init() {
        setSize(500,300);
        setTitle("显示图片和文本的表格");
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        initComponents();
        pack();
    }

   public void initComponents() {
       String[] columnNames = new String[]{"编号","文件"};

       Object[][] data = new Object[5][2];
       Icon icon = getFileIcon(filePath);
       data[0][0] = 10001;
       JLabel label = new JLabel(filePath.substring(filePath.lastIndexOf("\\")+1,filePath.length()));
       label.setIcon(icon);
       data[0][1] = label;
       TableModel tm = new DefaultTableModel(data,columnNames);
       table = new JTable(tm);
       table.setAutoscrolls(true);
       table.getColumnModel().getColumn(0).setPreferredWidth(50);
       table.getColumnModel().getColumn(1).setPreferredWidth(300);
       table.getColumnModel().getColumn(1).setCellRenderer(new JTableCellRender());

       JScrollPane jsp = new JScrollPane(table);
       getContentPane().add(jsp);
   }

   private Icon getFileIcon(String filePath) {
       File f = new File(filePath);
       if (f.exists()) {
           FileSystemView fsv = FileSystemView.getFileSystemView();
           Icon icon = fsv.getSystemIcon(f);
           return icon;
       }
       return null;
   }

    public static void main(String[] args) {
        IconAndTextTable iatt = new IconAndTextTable();
        iatt.init();
    }
}

class JTableCellRender extends JLabel implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        return (JLabel)value;
    }
}
 
 
 

你可能感兴趣的:(java)