Question

I have changed the cell render in JTable to show image instead of text using the following code:

base_table.getColumnModel().getColumn(3).setCellRenderer(new TableCellRenderer() {

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object value,
            boolean bln, boolean bln1, int i, int i1) {
        JLabel lbl = new JLabel();
        lbl.setIcon((ImageIcon) value);
        return lbl;
    }
});

Now, I'd like to be able to get the image for each row in the JTable in order to save it in database. How could I do that?

Was it helpful?

Solution

I can't resist just example for that

enter image description here enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private JLabel myLabel = new JLabel("waiting");
    private int pHeight = 40;
    private boolean runProcess = true;
    private int count = 0;

    public TableIcon() {
        ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
        ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
        ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
        String[] columnNames = {"Picture", "Description"};
        Object[][] data = {{errorIcon, "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model);
        table.setRowHeight(pHeight);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        myLabel.setPreferredSize(new Dimension(200, pHeight));
        myLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(myLabel, BorderLayout.SOUTH);
        new Thread(this).start();
    }

    public void run() {
        while (runProcess) {
            try {
                Thread.sleep(1250);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    ImageIcon myIcon = (ImageIcon) table.getModel().getValueAt(count, 0);
                    String lbl = "JTable Row at :  " + count;
                    myLabel.setIcon(myIcon);
                    myLabel.setText(lbl);
                    count++;
                    if (count > 2) {
                        count = 0;
                    }
                }
            });
        }
    }

    public static void main(String[] args) {
        TableIcon frame = new TableIcon();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }
}

OTHER TIPS

The data stored in a JTable can be found in its TableModel. But since it's your code, normally, that builds this TableModel (from a list or an array, typically), you should be able to get the icon from this list or array. Else, just use table.getModel().getValueAt(row, column), and cast it to an ImageIcon.

You should already have all the images in your table model. So you just have to get the images from the model, and then save them in your database.

In your cell renderer you have the type Object value, then you use (ImageIcon) value to cast it to an ImageIcon in lbl.setIcon((ImageIcon) value);

You can do the exaclty the same when you get the data from your model:

ImageIcon myIcon = 
         (ImageIcon) base_table.getModel().getValueAt(rowIndex, 3);

where 3 is your columnIndex for the column with images, and rowIndex is the row you want.

below is the correct image renderer class.

class SimpleCellRenderer extends DefaultTableCellRenderer{



    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) 

    {
         Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
               column);
      ((JLabel)cell).setIcon((Icon)value);
      ((JLabel)cell).setText("");
      ((JLabel)cell).setHorizontalAlignment(JLabel.CENTER);

      if (isSelected) {
         cell.setBackground(Color.white);
      } else {
         cell.setBackground(null);
      }
      //((AbstractTableModel)table.getModel()).fireTableCellUpdated(row,column);

      return cell;
   }


    }

below is the method from where everything gets filled automtically. private void formWindowOpened(java.awt.event.WindowEvent evt)

{                                  
        // TODO add your handling code here:

        fillIcon();  
    } 

   public void fillIcon() {
        int i,j,rowValue,colValue;
         int cols= student.getColumnCount();
         int rows=student.getRowCount();

         for(i =0 ;i<rows ;i++)
         {
             for(j=3; j<cols;j++)
             {
                 rowValue = i;
                 colValue = j;
                 String value = (String)student.getValueAt(rowValue, colValue);

                 if(value.equals("h"))//here h is the value stored in your database which is used to set some icon in place of value h.
{

            ImageIcon icon = new ImageIcon(getClass().getResource("dash.png"));
            student.setValueAt(icon, rowValue, colValue);
            student.getColumnModel().getColumn(colValue).setCellRenderer(new SimpleCellRenderer());
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top