0

I am trying to load image in a jTable based on database value.

String query = "SELECT ID, CATEGORY FROM TATTOO_LIB ORDER BY ID DESC";
try {
    conn = new data.connection().db();
    stmtt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmtt.executeQuery(query);
    while (rs.next()) {

        //I donot know how to write these lines here...

        File f = new File("C:/img/" + rs.getString(1) + ".jpg");
        ImageIcon icon = new ImageIcon(f);
        model.addRow(new Object[]{icon, rs.getString(1), rs.getString(2)});


    }
} catch(SQLException e ) {
    JOptionPane.showMessageDialog(null, "Error In Connection!!");
} finally {
    try {
        stmtt.close();
        rs.close();
        conn.close();
    } catch (SQLException e) {
    }

}

How can I load an Image in the first column based on the database value. I tried to follow this and this. But I am lost somewhere. Please help.

Community
  • 1
  • 1
Pranjal Choladhara
  • 845
  • 2
  • 14
  • 35

1 Answers1

2

Override getColumnClass() of the table model so the ImageIcon can be rendered correctly. See more at How to Use Tables - Concepts: Editors and Renderers

    DefaultTableModel model = new DefaultTableModel(colNames, 0) {
        @Override
        public Class<?> getColumnClass(int col) {
            switch(col) {
                case 0: return ImageIcon.class;
                default: return String.class;
            }
        }
    };

Also ImageIcon doesn't accept a File argument. You can use ImageIO.read() to obtain an Image to pass to the ImageIcon though

File f = new File("C:/img/"+rs.getString(1)+".jpg");
Image image = ImageIO.read(f);
ImageIcon icon = new ImageIcon(image);

You could just pass the string file path to the ImageIcon, but ImageIO will throw an exception is the path is incorrect, which is helpful

You'll probably want to set the row height and column width accordingly, also

table.setRowHeight(height);
TableColumn column = table.getColumn("ColumnIdentifier");
column.setWidth(150);
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720