0

I have been coding a simple JTable (Java) which stores name, food, drinks, etc. I tried to insert images into the JTable but the output seems weird

This is the button for choosing an image from my computer.

   public static ImageIcon ResizeImage(String ImagePath)
{   JLabel text1 = new JLabel();
   
    ImageIcon MyImage = new ImageIcon(ImagePath);
    Image img = MyImage.getImage();
    Image newImg = img.getScaledInstance(10,10, Image.SCALE_SMOOTH);
    ImageIcon image = new ImageIcon(newImg);
    
    return image;
}

btnChoose.addActionListener(new ActionListener(){
    
    @Override
    public void actionPerformed(ActionEvent e)
    {
       JFileChooser file = new JFileChooser();
      file.setCurrentDirectory(new File(System.getProperty("user.home")));
      //filter the files
      FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");
      file.addChoosableFileFilter(filter);
      int result = file.showSaveDialog(null);
          File selectedFile = file.getSelectedFile();
          String path = selectedFile.getAbsolutePath();
           text1.setIcon(ResizeImage(path));
           
        
    }
    }      );

After that, this is the add button that I use to insert data into the JTable

 Object[] row = new Object[6];
    
    // button add row
    btnAdd.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
           
           row[0]=text1.getIcon();
            ImageIcon icon = new ImageIcon(row[0].toString());
            
            text1.setIcon(icon);
   
           
            row[1] = textName.getText();
            row[2] = textFoodG.getText();
            row[3] = textDate.getText();
    row[4] = textDay.getText();
    row[5] = textDrink.getText();
            
            
           
            
            // add row to the model
           
            model.addRow(row);}});

The sample output:

enter image description here

Why does it come out"javax.swing..." on the image column? Is there a solution to make the image appear inside the cell? I apologize for any mistakes I did my research but I feel so frustrated that I can't figure out what is wrong with my code.

camickr
  • 316,400
  • 19
  • 155
  • 279
  • 2
    If you want to display an image in a JTable then you need to do two things: 1) add an Icon to the TableModel 2) override the `getColumnClass()` method to return `Icon.class` so the table can use an Icon renderer. See: https://stackoverflow.com/questions/4941372/how-to-insert-image-into-jtable-cell/4947154#4947154 for a basic example. – camickr Jun 11 '21 at 02:59

0 Answers0