user3387809
user3387809

Reputation: 3

add an image from Database into JTable

i am trying to add an image that is in my database in a column in JTable with a number and a code special to this image the problem is i got the number and the code but the image doesn't show i don't know why here is my code

String sql="SELECT id,chiffre,image FROM symbolique WHERE id  BETWEEN 200 and 205";
try{
    st=connexion.prepareStatement(sql);
    res=st.executeQuery();
    while(res.next()){
        int j=0;
        String [] code= new String[1000];
        String [] chiffre1=new String[100];
        code [j] = res.getString("id");
        chiffre1[j] = Integer.toString(res.getInt("chiffre"));
        Blob blob = res.getBlob("image");
        is2 = new BufferedInputStream(blob.getBinaryStream());
        Image raw = ImageIO.read(is2);
        ImageIcon icon  =new ImageIcon(raw);
        Object [][] data = new Object[200][100];
        data[j][1]= code [j];
        data[j][2]= chiffre1[j];
        data[j][3]=icon;
        j++;
        String title[] = {"image", "chiffre","code"};
        DefaultTableModel model = new DefaultTableModel(data, title);
        table.setModel(model);
    }
}catch(Exception e){
   JOptionPane.showMessageDialog(null, e);}
}

Upvotes: 0

Views: 885

Answers (2)

camickr
camickr

Reputation: 324118

This won't help solve the image problem but right now your code recreates the TableModel for every row in the ResultSet, which means you will only ever see one row of data.

  1. Since you have looping code you need to create an empty DefaultTableModel before the loop starts.
  2. Inside the loop you then use the addRow(...) method to add another row of data to the TableModel for every row in the ResultSet
  3. When you finish the loop then you use the model to create the JTable.

Did you add any debug code? Did you attempt to display the width/height of the image to confirm that you are reading the image properly? Why don't you do a simple test that tries to read and display an image in a JLabel first since using a JTable is more complicated than using a JLabel. Then once you get that working you can apply the knowledge to using a JTable.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109813

  • put Icon/ImageIcon to JTable better to the TableModel directly

  • you have to override getColumnClass for Icon/ImageIcon in XxxTableModel for showing this Object as image in the JTables view

  • for detailed informations (incl. working code examples) to read official Oracle tutorial - How to use Tables

Upvotes: 2

Related Questions