如何在JTable中显示图片?

时间:2015-07-25 21:26:21

标签: java image swing jtable blob

尝试在JTable内的单元格内显示图像时出现轻微问题,这会采用文本格式并显示图像本身。

E.G。 icon.toString()“返回:

enter image description here

我的代码:

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());
    }
}

任何人都知道如何纠正代码?

1 个答案:

答案 0 :(得分:2)

您需要覆盖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());
    }
}