我需要将 .txt 加载到JTable
with ,我在这里delimiter
找到了一个很好的示例
这是样本数据:
102|Beth Reiser||New York|(212)5558725
111|Dylan Ricci||Syracuse|(315)5554486
116|Brian Gugliuzza||Mamaroneck|(914)5553817
120|Gertrude Stein||Elmsford|(914)5553476
131|Daljit Sinnot||Bohemia|(516)5559811
这是我修改后的代码:
package Model;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class DataFileTableModel extends AbstractTableModel {
protected Vector data;
protected Vector columnNames ;
protected String datafile;
public DataFileTableModel(String f, String delimiter){
datafile = f;
initVectors(delimiter);
}
public void initVectors(String delimiter) {
String aLine ;
data = new Vector();
columnNames = new Vector();
int lineNum=0;
try {
FileInputStream fin = new FileInputStream(datafile);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
// extract column names
StringTokenizer st1 =
new StringTokenizer(br.readLine(), delimiter);
while(st1.hasMoreTokens())
columnNames.addElement(st1.nextToken());
// extract data
while ((aLine = br.readLine()) != null && lineNum<20) {
StringTokenizer st2 =
new StringTokenizer(aLine, delimiter);
lineNum++;
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 columnNames.size();
}
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount())
colName = (String)columnNames.elementAt(columnIndex);
return colName;
}
public Class getColumnClass(int columnIndex){
return String.class;
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
return;
}
}
根据数据,它会显示5列,但它只显示4列,第3列因为空而被跳过。我想将所有列显示到JTable
,我怎么能做到这一点?根据@ hovercraft-full-of-eels,当空列位于表格中间时,它可以成功显示,但它无法处理背面的空列。如何得到这个?
背面空列的数据样本:
102|Beth Reiser||New York|(212)5558725||||
111|Dylan Ricci||Syracuse|(315)5554486||||
116|Brian Gugliuzza||Mamaroneck|(914)5553817||||