简体   繁体   中英

JTable Custom TableCellRenderer displaying images

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM