简体   繁体   English

JTable自定义TableCellRenderer显示图像

[英]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. 我有一个JTable,我想根据单元格的内容显示一个图像,我理解要实现这一点,我必须实现自己的自定义单元格渲染器,但是,我已经有了第一张图像在单元格上绘制图像时,程序会在其他单元格上绘制图像,而不管其内容如何。 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. 预先感谢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. 在类的构造函数中读取图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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