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

7.8k views Asked by At

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?

1

There are 1 answers

4
Madhawa Priyashantha On BEST ANSWER

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

    }