我做了一些调查,问题似乎位于DefaultTableModel
。具体来说,在getColumnClass
方法中。当我在columnNames
String
数组中仅使用2列时:
(String[] columnNames = {"Icon", "Filename"})
一切正常。但是当我添加第三列时:
(String[] columnNames = {"Icon", "Filename", "Size"}):
我开始收到NullPointerException
错误。
我做错了什么?
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);
}
}