简体   繁体   中英

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

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|6847654127v|Kandy|

I want to populate my 'jTable' with the data from this text file. below is my code so far which doesn't work. When I execute the program nothing is displayed on the table.

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

} 

Can someone please help me?

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM