I did some investigating and it appears the issue is located in the DefaultTableModel
. Specifically, in the getColumnClass
method. When I use only 2 columns in the columnNames
String
array:
(String[] columnNames = {"Icon", "Filename"})
Everything works fine. But when I add a third column:
(String[] columnNames = {"Icon", "Filename", "Size"}):
I start getting the NullPointerException
error.
What am I doing wrong?
package jtablefun;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableModel;
public class JtableFun extends JFrame{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new JtableFun().show();
}
public JtableFun(){
getContentPane().setLayout(new GridBagLayout());
//String s[] = f.list();
buildTable();
pack();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void buildTable(){
File f = new File("/");
File[] fl = f.listFiles();
String fileNames[] = f.list();
Icon iconArray[] = new Icon[fileNames.length];
//Icon icon = FileSystemView.getFileSystemView().getSystemIcon(f);
for(int i=0; i<fileNames.length; i++){
iconArray[i] = FileSystemView.getFileSystemView().getSystemIcon(fl[i]);
}
String[] columnNames = {"Icon", "Filename", "Size"};
Object[][] data = new Object[fl.length][(fl.length * 2)];
for(int row=0; row<fl.length; row++){
for(int column=0; column<2; column++){
if(column == 0){
data[row][column]= iconArray[row];
}else if(column == 1){
data[row][column]= fileNames[row];
}else if(column == 3){
//data[row][column]= fl[row].length();
}
}
}
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
GridBagConstraints g = new GridBagConstraints();
g.gridx =0;
g.gridy =0;
getContentPane().add(table,g);
}
}