ImageIcon in JTableCell

67 views Asked by At

I am having an issue adding an ImageIcon to my JLabel in my JTable. So far I am entirely able to manipulate the cell based on the value of the data in the cell however whenever I try to add in an image I am only seeing the text.

Table Renderer

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);
    }

}

This is the Renderer I am using in my 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;
}

The color and text set just fine but the icon will not display. Any ideas would be appreciated!

EDIT- Suggestions by VGR and Camickr

Your advice was spot on and resolved the issue! Take a look at the redone portion. I am very grateful. Thanks guys!

 //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;
}
}
1

There are 1 answers

0
VGR On BEST ANSWER

The ImageIcon constructor documentation makes it clear that the string argument is a filename. Unless your system has a Res directory in the root of the file system, you probably meant to do new ImageIcon(getClass().getResource("/Res/online.jpg")) or new ImageIcon(getClass().getResource("/online.jpg")).

Note that your else clause should be setting the icon to null, since a single renderer may be used for multiple table cells.