java - JTableCell 中的图像图标

标签 java swing jtable imageicon renderer

我在将 ImageIcon 添加到 JTable 中的 JLabel 时遇到问题。到目前为止,我完全能够根据单元格中数据的值来操作单元格,但是每当我尝试添加图像时,我只能看到文本。

表格渲染器

class DeviceTableModel extends AbstractTableModel {
    private Object[][] data = Globals.getArray();
    private String[] columnNames = {"Name","Status","Description"};


    @Override
    public int getRowCount() {
        return data.length;
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }

    @Override
    public String getColumnName(int col) {
        return columnNames[col];
    }

    @Override
    public Class getColumnClass(int c) {
        return getValueAt(0,c).getClass();
    }

    @Override
    public void setValueAt(Object value, int row, int col) {
        data[row][col] = value;
        fireTableCellUpdated(row,col);
    }

}

这是我在 JTable 中使用的渲染器。

 @Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
    JLabel comp = (JLabel)super.prepareRenderer(renderer, row, col);
    Object value = getModel().getValueAt(row, col);

    if (value.equals("online")) {
        comp.setIcon(new ImageIcon("/Res/online.png"));
        comp.setBackground(Color.green);
    }else {
        comp.setBackground(Color.white);
    }

    return comp;
}

颜色和文本设置得很好,但图标不会显示。任何想法将不胜感激!

编辑 - VGR 和 Camickr 的建议

您的建议很准确,解决了问题!看看重做的部分。我很感激。谢谢大家!

 //preloaded just added here to show. 
 ImageIcon icon = new  ImageIcon(getClass().getResource("/Res/onlineIcon.png"));


 @Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
    JLabel comp = (JLabel)super.prepareRenderer(renderer, row, col);
    Object value = getModel().getValueAt(row, col);

    if (value.equals("online")) {
        comp.setIcon(icon);
        comp.setBackground(new Color(173,255,92));
    }else {
        comp.setIcon(null);
        comp.setBackground(Color.white);
    }
    return comp;
}
}

最佳答案

ImageIcon constructor documentation清楚地表明字符串参数是文件名。除非您的系统在文件系统的根目录中有 Res 目录,否则您可能打算执行 new ImageIcon(getClass().getResource("/Res/online.jpg"))new ImageIcon(getClass().getResource("/online.jpg"))

请注意,您的 else 子句应将图标设置为 null,因为单个渲染器可用于多个表格单元格。

关于java - JTableCell 中的图像图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783327/

相关文章:

java - 在java中制作一个程序自动添加文本字段

java - 如何使 Autowired 在 Configuration 类中工作?

java - Swing 中的进度对话框

java - 如何在jTable中显示数据库内容?

java - 允许 JTable 仅由程序编辑,但允许用户从中复制数据

java对一组数据的不同排序方法

java - 运行 java 应用程序后创建并显示标签

java - 将油漆从一个面板转移到另一个面板

java - 在 java swing 中单击按钮时创建具有新名称的类的新对象

java - JTable 3 字段数组列表