Java Swing How to - Insert Image into JTable








Question

We would like to know how to insert Image into JTable.

Answer

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
//from  ww  w  . j  ava  2 s. co  m
public class Main extends JFrame {
  public Main() {
    ImageIcon aboutIcon = new ImageIcon("about16.gif");
    ImageIcon addIcon = new ImageIcon("add16.gif");
    ImageIcon copyIcon = new ImageIcon("copy16.gif");

    String[] columnNames = { "Picture", "Description" };
    Object[][] data = { { aboutIcon, "About" }, { addIcon, "Add" },
        { copyIcon, "Copy" }, };

    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    JTable table = new JTable(model) {
      public Class getColumnClass(int column) {
        return (column == 0) ? Icon.class : Object.class;
      }
    };
    table.setPreferredScrollableViewportSize(table.getPreferredSize());

    JScrollPane scrollPane = new JScrollPane(table);
    getContentPane().add(scrollPane);
  }

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

}