Reputation: 83
I am newbee in Jtable swing ,I want to set the image icon to particular cell of Jtable,
So I tried following code.
ImageIcon addIcon = new ImageIcon("addIcon.gif"); //addIcon.gif is stored in the resource packaage
table.setModel(new javax.swing.table.DefaultTableModel
(
new Object [][]
{
{
rowNumber, null, null, null,addIcon
},
{
null,null ,"Total" ,"0.0","Get Total"
}
},
new String []
{
"No.", "Item", "Weight", "Amount","#"
}
)
{
@Override
public Class<?> getColumnClass(int c)
{
return getValueAt(0, c).getClass();
}
}
);
But instead of Icon, I am getting the "addIcon.gif" string in that jTable cell. What is the mistake I did here.
Please help.
Upvotes: 0
Views: 1716
Reputation: 324118
You can't just override the getColumnClass(...)
method because that class will be used to determine the renderer for all rows for a given column in the table.
For specific cell rendering you can override the getCellRenderer(...)
method fo the table:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
ImageIcon addIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"No.", "Item", "Weight", "Amount","#"};
Object[][] data =
{
{"123", null, null, null, addIcon},
{null, null ,"Total" ,"0.0", "Get Total"}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
@Override
public TableCellRenderer getCellRenderer(int row, int column)
{
int modelColumn = convertColumnIndexToModel(column);
if (modelColumn == 4 && row == 0)
{
return getDefaultRenderer( Icon.class );
}
else
return super.getCellRenderer(row, column);
}
};
add( new JScrollPane( table ) );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
This is an example of a SSCCE
. A SSCCE should be included with all questions to demonstrate your problem.
Upvotes: 1
Reputation: 1405
You need to implement your own TableCellRenderer: https://docs.oracle.com/javase/8/docs/api/javax/swing/table/TableCellRenderer.html . The table model only holds the icon, it does no drawing. Drawing is done by cell renderers (to separate UI and data). See also the JTable tutorial about custom cell renderers: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer
Upvotes: 1