How to get Icon from JTable

不羁的心 提交于 2019-11-27 05:38:21

I can't resist just example for that

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

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());
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!