如何在jtable中显示图片?

5gfr0r5j  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(456)

我有一个小问题,当我试图显示一个图像在一个细胞内的计算机 JTable ,它采用文本格式并显示图像本身。
例如 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());
    }
}

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

ncecgwcz

ncecgwcz1#

您需要重写tablemodel中的getcolumnclass(int col)方法,以便它为要显示imageicon的列返回imageicon.class,并将imageicon直接分配给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());
    }
}

相关问题