我在将 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/