0

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
user2426634
  • 25
  • 1
  • 2
  • 5

1 Answers1

4

Don't forget to invoke:

super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

at the start of the method so you get the default settings of the renderer.

If the above doesn't fix the problem then your code may need to be something like:

if (value.toString().equals("X"))
{
    URL test = getClass().getResource(resources/icon.png");
    setIcon(new ImageIcon(test));
    setText("");
}
else
{
    setIcon(null);
    setText(value.toString());
}

Also, you should never read the image in the renderer. The render gets called multiple times so you don't want to read the image every time. Read the image in the constructor of the class.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • `UIManager.getIcon("html.pendingImage")` is a handy placeholder. – trashgod May 28 '13 at 01:02
  • I would like to thank you a million times, I cannot believe something so silly was causing this much problem xD, this fixed it for me: if (value.toString().equals("X")) { setIcon(new ImageIcon(test)); setText(""); } else { setIcon(null); setText(value.toString()); } – user2426634 May 28 '13 at 12:19