Q: How do you add a icon to a JTable

I am trying to find out how to add an icon as a column of a JTable.Can anyone help me?Thanks in advance
[131 byte] By [loughead] at [2007-9-26 3:32:08]
# 1

this is a little tricky. what exactly are u trying to do? add an icon based on a certain value in that cell or merely add the same icon to all the cells in that column?

i have a piece that adds a lock icon if the cell is not null.

lemme know what exactly you are looking for and i will post the code.

rapte at 2007-6-29 11:59:20 > top of Java-index,Archived Forums,Java Programming...
# 2
I want to add the icon to the jTable based on a value
loughead at 2007-6-29 11:59:20 > top of Java-index,Archived Forums,Java Programming...
# 3
I don't think you have to do anything special, JTable can handle ImageIcons automatically.
chuanhaochiu at 2007-6-29 11:59:20 > top of Java-index,Archived Forums,Java Programming...
# 4

ok, this is a little involved. you need something to build your table model. i assume you have something called MyTableModel that extends AbstractTableModel

now, heres the code (its all in my main class):

public void setUpTableCells()

{

TableColumn col=null;

col=repairQTable.getColumnModel().getColumn(1);

col.setPreferredWidth(300);

lockRenderer mylockrenderer=new lockRenderer();

col.setCellRenderer(mylockrenderer);

}

class lockRenderer extends JLabel implements TableCellRenderer

{

public lockRenderer()

{

super();

}

public Component getTableCellRendererComponent(JTable table,Object locked,boolean isSelected,boolean hasFocus,int row, int column)

{

JLabel retLabel;

if(locked==null)//locked is a value passed to the function. it holds the value of a certain row,col in my table model

{

retLabel=new JLabel();

retLabel.setToolTipText("");

}

else

{

retLabel=new JLabel("",new ImageIcon("images/lockSmall.gif",""),JLabel.CENTER);

retLabel.setToolTipText("Locked by " + locked);

}

setBorder(BorderFactory.createMatteBorder(2,5,2,5,table.getBackground()));

return retLabel;

}

}

I hope that makes sense. it actually does work for me.

rapte at 2007-6-29 11:59:20 > top of Java-index,Archived Forums,Java Programming...
# 5
Does the cell in the table model have to be setup to handle an icon? When I add the icon all I get is a string specifying where the icon is located.
loughead at 2007-6-29 11:59:20 > top of Java-index,Archived Forums,Java Programming...
# 6
did u see my code? i have a cell renderer called lockRenderer. i make that the renderer for the columns that need to have the lock icon.
rapte at 2007-6-29 11:59:20 > top of Java-index,Archived Forums,Java Programming...