Add an image or icon in JTable
The JTable class provides a method for inserting icons or images. JTable needs to specify the type of objects stored in the table column so that it can choose the appropriate rendering. This is done by calling the method getColumnClass(...):public Class getColumnClass(int column)Java determines whether you have specified a renderer of JTable or not, otherwise JTable invokes the template and calls the getColumnClass() which retrieves the cell type in the first row. Then, it compares it with a list of data types in which the renditions are saved. This list is initiated by JTable, but you can add or edit. Renderings include ImageIcon and Icon.
{
return getValueAt(0, column).getClass();
}
The following example shows how to add images to a column:
import javax.swing.*;Result after execution:
import javax.swing.table.*;
public class Table_image extends JFrame
{
public Table_image()
{
ImageIcon icon1 = new ImageIcon("1.png");
ImageIcon icon2 = new ImageIcon("2.png");
ImageIcon icon3 = new ImageIcon("3.png");
ImageIcon icon4 = new ImageIcon("4.png");
String[] Title = {"Operating System", "Popularity"};
Object[][] data =
{
{icon1, "Android: 76.6%"},
{icon2, "IOS: 19.7%"},
{icon3, "Windows Phone: 2.8%"},
{icon4, "BlackBerry OS: 1%"},
};
DefaultTableModel template = new DefaultTableModel(data, Title);
JTable table = new JTable( template )
{
/*automatic detection of data types
*of all columns
*/
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
//change row height
table.setRowHeight(100);
JScrollPane scrollPane = new JScrollPane( table);
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
Table_image frame = new Table_image();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
If you don't implement the getColumnClass, the column will contain text(file name) and not images. For example, instead of inserting the Android logo, JTable will display "1.png".
If you are using your own template that inherits from AbstractTableModel, don't forget to implement the getColumnClass in the model class.
class Model extends AbstractTableModel{Read more about editors and renderers on the official java website: Editors and Renderers.
private Object[][] data;
private String[] title;
public Model(Object[][] data, String[] title){
this.data = data;
this.title = title;
}
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
public int getColumnCount() {
return this.title.length;
}
public int getRowCount() {
return this.data.length;
}
public Object getValueAt(int row, int col) {
return this.data[row][col];
}
}