您好我需要将文本文件导入Jtable。我必须将每个列存储到一个单独的数组中,所以我想为表创建一个2D数组,并为每个列创建一个数组。 (9列,共20行)
我迄今为止所做的就是导入文本文件并将其显示在Jtable中。 我必须使用的数据类型是int,string和double(或float),因为我必须创建作为student表,其中将显示其ID号(int)名称,地址ect(字符串)和成绩(double)能够用等级进行计算。
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// When the window is opened, the information from the text file will be loaded into the table (tblStudentDetails)
try {
BufferedReader br = new BufferedReader(new FileReader ("C:\\Users\\XXX\\NetBeansProjects\\StudentDetailsJava\\lib\\StudentDetails.txt"));
//Get the first line
//Get the columns name from the first line
// Set columns name to the tblStudentDetails model
String firstLine = br.readLine().trim(); // Reading the file line (row) of the text file
// while(firstLine !=null) {
String[] columnsName = firstLine.split("\t"); // The coloums are split by tab
DefaultTableModel model = (DefaultTableModel)tblStudentDetails.getModel();
model.setColumnIdentifiers(columnsName);
// Get lines from txt file
Object[] tableLines = br.lines().toArray();
// Extract data from lines
// Set data to tblStudentsData model
for (Object tableLine : tableLines) {
String line = tableLine.toString().trim();
String[] dataRow = line.split("\t");
{
model.addRow(dataRow);
}
}
br.close();
} catch (Exception ex) {
Logger.getLogger(StudentTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
到目前为止,这是我所拥有的,在你们杀了我之前,我花了3天时间试图让这个工作起来,我已经尝试了几乎我在这个网站上找到的所有解决方案都无济于事。
我已经能够创建一个2D数组,但是在阅读文本文件或将其导入Jtable时,我实际上无法使其工作。有人帮忙! 第一年的学生,所以我肯定是一个新手,我的任务即将到期,我不能继续解决这个问题!
谢谢! - x太太
另外 文本文件看起来像这样(由制表符分隔,所以第一行太长,但它导入Jtable就好了)
答案 0 :(得分:0)
试试这段代码:
Scanner input = new Scanner(new File(FILE_NAME));
int rows = 0;
String[] columnsName = null;
if (input.hasNext()) {
columnsName = input.nextLine().split("\t");
} else {
return;
}
while (input.hasNextLine()) {
input.nextLine();
++rows;
}
String[][] a = new String[rows][columnsName.length];
input.close();
input = new Scanner(new File(FILE_NAME));
if (input.hasNextLine()) {
input.nextLine();
}
for (int i = 0; i < rows; i++) {
a[i] = input.nextLine().split("\t");
}
JTable jt = new JTable(a, columnsName);