I need to display an image in one of jTable cells.
I wrote this:class ImageRenderer extends DefaultTableCellRenderer {
JLabel lbl = new JLabel();
public Compo开发者_如何学Pythonnent getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
lbl.setText((String) value);
lbl.setIcon(new ImageIcon("/home/ariyan/Desktop/71290452.jpg"));
return lbl;
}
}
and then used it as this:
jTable1.getColumn(0).setCellRenderer(new ImageRenderer());
But this didn't work
How I can do that?Thanks
JTable already provides a default renderer for images. You just need to tell the table what type of data is contained in each column and it will choose the best renderer:
a) override the getColumnClass() method of the JTable or the TableModel to return the class of data in the column. In this case you should return an Icon.class.
b) add an ImageIcon to the table model.
Now the JTable will use the default Icon renderer for that column.
Hmm: jTable1.getColumnModel().getColumn(0).setCellRenderer(new ImageRenderer());
perhaps?
Here's the relevant extract of some quick test code I put together to quickly verify my guess. It displays icons from a folder (it assumes all files in a folder are icons, so you should test it with something like an XDG icon theme sub directory). Install table model first then add the cell renderer on the columns:
class Renderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent (JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
if(isSelected) {
this.setBackground(table.getSelectionBackground());
this.setForeground(table.getSelectionForeground());
}
else {
this.setBackground(table.getBackground());
this.setForeground(table.getForeground());
}
if(column == 0) {
this.setText(list[row]);
}
else {
// edit as appropriate for your icon theme
this.setIcon(new ImageIcon("/usr/share/icons/default.kde4/16x16/apps/"+list[row]));
}
return this;
}
}
class Model extends DefaultTableModel {
@Override
public boolean isCellEditable (int row, int column) {
return false;
}
@Override
public Object getValueAt (int row, int column) {
return list[row];
}
@Override
public int getRowCount () {
return list.length;
}
@Override
public int getColumnCount () {
return 2;
}
@Override
public String getColumnName (int column) {
return column == 0? "Name" : "Preview";
}
@Override
public Class<?> getColumnClass (int columnIndex) {
return String.class;
}
}
// edit base directory as appropriate for your icon theme of choice
static String[] list=new File("/usr/share/icons/default.kde4/16x16/apps/").list();
精彩评论