populate a 'JTable' with values from a '.txt' file

前端 未结 1 688
南笙
南笙 2021-01-24 13:05

I\'m new to java and I have a text file like this

0784879541|P. K.|Tharindu|745874654v|Colombo|
0714786542|H. R.|Kamal|654124784v|Colombo|
0114784544|H. P.|Gamage         


        
1条回答
  •  别那么骄傲
    2021-01-24 13:39

    you need to change your to something like this.you need to reset vector data = new Vector(); each time when you read new line otherwise it contain first row + second row + so on.and also you can call dtm.setRowCount(0); to avoid empty initial rows . and you need only to add rows the problem of your comment[cell contain lot of columns] is because of dtm.addRow(new Object[]{columns, data}) use dtm.addRow(data); instead and problem will be fixed

    code

    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();
            }
    
        }
    

    0 讨论(0)
提交回复
热议问题