我需要将文本文件内容拉入jtable并显示它们。我已经尝试了各种代码,它会挂起并出错。我认为它一遍又一遍地重复表值,但我不明白为什么会发生这种情况,因为我调用了reader.close()命令,如果没有下一行,读者不应该继续。
这是DefaultTableModel代码:
String columns[] = { "Name", "Age", "Email Address", "Cell Number" };
JTable contactTable = new JTable();
DefaultTableModel tableModel;
// table with 4 columns
tableModel = new DefaultTableModel(0,4);
tableModel.setColumnIdentifiers(columns);
contactTable.setModel(tableModel);
以下是文本文件代码的读取:
void showContacts(){
String line;
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null)) //this gives me an error???
{
tableModel.addRow(line.split(", ")); //this has a comma and a space bc that is how the file is written to
}
reader.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Buffered Reader issue.");
}
}
这是文本文件内容:
Name, Age, Email Address, Cell Number,
John Smith, 21, jsmith@site.com, 1234564789,
答案 0 :(得分:1)
更改此行:
while((line = reader.readLine()) != null))
到
while((line = reader.readLine()) != null)