我是Java新手,我有一个像这样的文本文件
0784879541|P. K.|Tharindu|745874654v|Colombo| 0714786542|H. R.|Kamal|654124784v|Colombo| 0114784544|H. P.|Gamage|6847654127v|Kandy|
我想用此文本文件中的数据填充“ jTable”。下面是到目前为止我的代码不起作用。当我执行程序时,表上没有任何显示。
private void formWindowOpened(java.awt.event.WindowEvent evt) { String line = null; DefaultTableModel dtm = (DefaultTableModel) PhoneBookTable.getModel(); try { BufferedReader br = new BufferedReader(new FileReader(file)); 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(); dtm.addRow(new Object[]{columns, data});//add here } catch (Exception e) { e.printStackTrace(); } }
有人可以帮帮我吗?
您需要将其更改为以下内容。data = new Vector();每次读取新行时,都需要重置矢量,否则它包含第一行+第二行+以此类推。您还可以调用dtm.setRowCount(0);以避免初始行为空。并且您只需要添加行,您的注释[单元格包含很多列]的问题是由于 dtm.addRow(new Object[]{columns, data})使用dtm.addRow(data);而引起的,问题将得到解决
data = new Vector();
dtm.setRowCount(0);
dtm.addRow(new Object[]{columns, data})
dtm.addRow(data);
码
private void formWindowOpened(java.awt.event.WindowEvent evt) { String line = null; DefaultTableModel dtm = (DefaultTableModel) PhoneBookTable.getModel(); try { BufferedReader br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { data = new Vector();// this is important StringTokenizer st1 = new StringTokenizer(line, "|"); while (st1.hasMoreTokens()) { String nextToken = st1.nextToken(); data.add(nextToken); System.out.println(nextToken); } System.out.println(data); dtm.addRow(data);//add here System.out.println("................................."); } br.close(); } catch (Exception e) { e.printStackTrace(); } }