我尝试使用下面的代码在JTable中显示ImageIcons。但是当我运行程序时,jTable只显示一个空白区域。 p1.getPicture();来自数据库。所以基本上,有没有办法修改下面的代码,以便有一种方法在图片中显示imageicon ???
package Tables;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import Entity.*;
public class ProfileTable extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private int rowCount, colCount;
private String[] columnNames = {"ClickId", "Name", "Gender", "Website", "Hobbies","Favourite Food", "DP"};
private Object [][] data;
private ImageIcon [][] icons;
public ProfileTable(ArrayList<Profile> listOfObjects) {
rowCount = listOfObjects.size();
colCount = columnNames.length;
data = new Object[rowCount][colCount];
//icons = new ImageIcon[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
/*Copy an ArrayList element to an instance of MyObject*/
Profile p1 = (Profile)(listOfObjects.get(i));
p1.retrieveProfile();
data[i][0] = p1.getClickId();
data[i][1] = p1.getFirstName();
data[i][2] = p1.getGender();
data[i][3] = p1.getWebsite();
data[i][4] = p1.getHobbies();
data[i][5] = p1.getFood();
icons[i][6] = new ImageIcon(p1.getPicture());
}
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return colCount;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return rowCount;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return data[rowIndex][columnIndex];
}
public String getColumnName(int col) {
return columnNames[col];
}
}
答案 0 :(得分:2)
覆盖TableModel中的getColumnClass
以返回第6列的ImageIcon:
@Override
public Class getColumnClass(int columnIndex) {
if(columnIndex == 6){
return ImageIcon.class;
}
return Object.class;
}
答案 1 :(得分:0)
使用它更简单但为列中的所有行设置图标,但您始终可以根据需要修改单元格:
public Class TableRender extend Jtable{
private void setComboColumn(JTable table, TableColumn Column,
String filepath) {
ImageIcon icon = new ImageIcon(filepath);
sportColumn.setCellEditor(new DefaultCellEditor(icon));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("icon");
Column.setCellRenderer(renderer);
}
}