本文介绍了如何在 JTable 中显示图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 JTable 中的单元格内显示图像时遇到一个小问题,它采用文本格式并显示图像本身.

I have a slight problem when trying to display an image on inside a cell in JTable, this takes a text format and shows the image itself.

E.G.icon.toString()" 返回:

我的代码:

public void loading() {
    try {
        String[]title = {"First Name","Last Name","Picture"};

        String sql="select * from users";
        model = new DefaultTableModel(null,title);
        st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        String[]fila = new String[4];

        while(rs.next()){
            fila[0] = rs.getString("fna");
            fila[1] = rs.getString("lna");
            byte[] imgBytes = rs.getBytes("pic");
            Blob blob = new javax.sql.rowset.serial.SerialBlob(imgBytes);
            BufferedImage image = null;
            try (InputStream is = blob.getBinaryStream()) {
                image = ImageIO.read(is);
                ImageIcon icon = new ImageIcon(image);
                fila[2] = icon.toString();
            } catch (IOException exp) {
                exp.printStackTrace();
            }
            model.addRow(fila);
        }
        tbl.setModel(model);
    }
    catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
}

有人知道如何更正代码吗?

Anyone knows how the code can be corrected?

推荐答案

您需要覆盖 TableModel 中的 getColumnClass(int col) 方法,以便它为要显示 ImageIcon 的列返回 ImageIcon.class,并分配ImageIcon 直接到fila[2]:

You need to override the getColumnClass(int col) method in your TableModel so that it returns ImageIcon.class for the columns you want to display an ImageIcon, and assign the ImageIcon directly to fila[2]:

public void loading() {
    try {
        String[]title = {"First Name","Last Name","Picture"};
        String sql="select * from users";
        model = new DefaultTableModel(null,title){
            @Override
            public Class<?> getColumnClass(int column) {
                if (column==2) return ImageIcon.class;
                return Object.class;
            }
        }
        st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        Object[]fila = new Object[4];
        while(rs.next()){
            fila[0] = rs.getString("fna");
            fila[1] = rs.getString("lna");
            fila[2] = new ImageIcon(rs.getBytes("pic"));
            model.addRow(fila);
        }
        tbl.setModel(model);
    }
    catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
}

这篇关于如何在 JTable 中显示图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 04:09