2011-02-09 80 views
0

我嘗試使用下面的代碼在JTable中顯示ImageIcons。但是當我運行該程序時,jTable只顯示一個空的空間。 p1.getPicture();來自數據庫。所以基本上,有沒有辦法修改下面的代碼,以便有一種方法來顯示圖片中的圖片?在jTable中顯示ImageIcons

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

你的程序書面將無法正常運行:`圖標[I] [6] =`...要麼不能編譯,或者產生一個NullPointerException異常;嘗試將它改爲`data [i] [6]` – 2011-02-09 14:46:02

回答

2

覆蓋getColumnClass在TableModel返回一個ImageIcon與第6列:

@Override 
public Class getColumnClass(int columnIndex) { 
    if(columnIndex == 6){ 
     return ImageIcon.class; 
    } 
    return Object.class; 
} 
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); 
} 
}