我的文本文件包含以下数据:sample.txt
MEMHEAD 1 1 NA SetString srcCode
MEMHEAD 1 2 NA SetString memIdnum
LGLNAME 1 5 NA SetString onmfirst
我创建的MyClassModel
类扩展AbstractTableModel
为:
public class MyClassModel extends AbstractTableModel
{
Vector data;
Vector columns;
public MyTableModel() {
String line;
try {
FileInputStream fis = new FileInputStream("sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), ",");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, ",");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return columns.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
}
}
通过这种方式,我从文件中检索数据。现在,当我JTable
使用table.setModel(MyTableModel)
. 我得到一个NullPointerException
.
继续:
文本文件数据显示在 JTable 中,但 JTable 还包含一些带有一些垃圾数据的额外行,当我按下这些行时
java.lang.ArrayIndexOutOfBoundsException: 180 >= 180
,会引发此异常。但是,我发现线路有问题
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount()) + columnIndex);
}
但不知道是什么问题。请帮忙。