I have a JTable which I would like to display an image depending on the content of a cell, I understand in order to accomplish this I have to implement my own custom cell renderer, which I have already, however, as soon as the first image is drawn on the cell the programme draws the image on other cells regardless of their content. I have tried pretty much everything and have also scoured the internet for a solution, all with no avail. Here is my code:
public class GameBoard extends JTable
{
public GameBoard()
{
super(new GameBoardModel());
setFocusable(false);
setCellSelectionEnabled(true);
setRowHeight(26);
TableColumn column = null;
for (int i = 0; i < getColumnCount(); i++)
{
column = getColumnModel().getColumn(i);
column.setPreferredWidth(26);
}
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setDefaultRenderer(Object.class, new CellRenderer());
}
private class CellRenderer extends DefaultTableCellRenderer
{
private CellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column)
{
if (value.toString().equals("X"))
{
URL test = getClass().getResource(resources/icon.png");
setIcon(new ImageIcon(test));
}
else
setText(value.toString());
return this;
}
}
Forgive me if I'm doing something silly somewhere along those lines. . .
Thanks in advance, Zig.