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

陌路散爱 提交于 2019-12-20 07:32:06

问题


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

0786160384|P. K.|Tharindu|912921549v|Colombo|
0711495765|P. K.|Gamini|657414589v|Colombo|
0114756199|H. P.|Weerasigha|657895478v|Kandy|

I want to populate my 'jTable' with 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?

below is my whole code

package Geo;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import java.text.*;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;

public class PrintGUI extends javax.swing.JFrame {

File file, tempFile;
FileReader fileReader;
FileWriter fileWriter;
ArrayList ClientList;
Vector data;
Vector columns;

public PrintGUI() {
    initComponents();
    this.setIconImage(new ImageIcon(getClass().getResource("/Images/icon.png")).getImage());
    file = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\phonebook.txt");
    tempFile = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\tempphonebook.txt");
}

public void toExcel(JTable PhoneBook, File file) {
    try {
        TableModel model = PhoneBook.getModel();
        FileWriter excel = new FileWriter(file);

        for (int i = 0; i < model.getColumnCount(); i++) {
            excel.write(model.getColumnName(i) + "\t");
        }

        excel.write("\n");

        for (int i = 0; i < model.getRowCount(); i++) {
            for (int j = 0; j < model.getColumnCount(); j++) {
                excel.write(model.getValueAt(i, j).toString() + "\t");
            }
            excel.write("\n");
        }

        excel.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    Export2ExcelButton = new javax.swing.JButton();
    Export2Text = new javax.swing.JButton();
    PrintButton = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    PhoneBookTable = new javax.swing.JTable();
    Background = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Print");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowOpened(java.awt.event.WindowEvent evt) {
            formWindowOpened(evt);
        }
    });
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    Export2ExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Logos-Excel-icon.png"))); // NOI18N
    Export2ExcelButton.setText("Export to Excel");
    Export2ExcelButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            Export2ExcelButtonActionPerformed(evt);
        }
    });
    getContentPane().add(Export2ExcelButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 350, 130, 30));

    Export2Text.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/File-TXT-icon.png"))); // NOI18N
    Export2Text.setText("Export to Text");
    Export2Text.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            Export2TextActionPerformed(evt);
        }
    });
    getContentPane().add(Export2Text, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 350, 130, 30));

    PrintButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Print-icon.png"))); // NOI18N
    PrintButton.setText("Print");
    PrintButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            PrintButtonActionPerformed(evt);
        }
    });
    getContentPane().add(PrintButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 350, 130, 30));

    PhoneBookTable.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null}
        },
        new String [] {
            "Phone No", "First Name", "Last Name", "NIC", "City"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    PhoneBookTable.setSelectionBackground(new java.awt.Color(255, 255, 0));
    PhoneBookTable.setSelectionForeground(new java.awt.Color(51, 51, 51));
    jScrollPane1.setViewportView(PhoneBookTable);

    getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 560, 310));

    Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/background.jpg"))); // NOI18N
    getContentPane().add(Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 600, 400));

    pack();
    setLocationRelativeTo(null);
}// </editor-fold>                        

private void Export2ExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    try {
        JFileChooser fc = new JFileChooser();
        int option = fc.showSaveDialog(PrintGUI.this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try {
                String filename = fc.getSelectedFile().getName();
                String path = fc.getSelectedFile().getParentFile().getPath();

                int len = filename.length();
                String ext = "";
                String file = "";

                if (len > 4) {
                    ext = filename.substring(len - 4, len);
                }

                if (ext.equals(".xls")) {
                    file = path + "\\" + filename;
                } else {
                    file = path + "\\" + filename + ".xls";
                }
                toExcel(PhoneBookTable, new File(file));
                int answer = JOptionPane.showConfirmDialog(null, "Would you like to open the exported file?", "Successfully exported!", option);
                if (answer == JOptionPane.YES_OPTION) {
                    try {
                        Desktop dt = Desktop.getDesktop();
                        dt.open(new File(file));

                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, e);
                    }
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}                                                  

private void PrintButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    MessageFormat header = new MessageFormat("Phone Book");
    MessageFormat footer = new MessageFormat("Page{0,number,integer}");

    try {
        PhoneBookTable.print(JTable.PrintMode.NORMAL, header, footer);
    } catch (java.awt.print.PrinterException e) {
        System.err.format("Cannot print %s$n", e.getMessage());
    }
}                                           

private void Export2TextActionPerformed(java.awt.event.ActionEvent evt) {                                            

    try {
        JFileChooser fc = new JFileChooser();
        int option = fc.showSaveDialog(PrintGUI.this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try {
                String filename = fc.getSelectedFile().getName();
                String path = fc.getSelectedFile().getParentFile().getPath();

                int len = filename.length();
                String ext = "";
                String file = "";

                if (len > 4) {
                    ext = filename.substring(len - 4, len);
                }

                if (ext.equals(".txt")) {
                    file = path + "\\" + filename;
                } else {
                    file = path + "\\" + filename + ".txt";
                }
                FileWriter fw = new FileWriter(file);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write("Phone No      First Name      Last Name       NIC     City");
                bw.newLine();
                bw.write("-----------------------------------------------------------");
                bw.newLine();

                for (int i = 0; i < PhoneBookTable.getRowCount(); i++) {
                    for (int j = 0; j < PhoneBookTable.getColumnCount(); j++) {
                        bw.write(PhoneBookTable.getModel().getValueAt(i, j) + "    ");
                    }
                    bw.newLine();

                }
                bw.close();
                fw.close();
                int answer = JOptionPane.showConfirmDialog(null, "Would you like to open the exported file?", "Successfully exported!", option);
                if (answer == JOptionPane.YES_OPTION) {
                    try {
                        Desktop dt = Desktop.getDesktop();
                        dt.open(new File(file));

                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, e);
                    }
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}                                           

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

}                                 

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;

            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PrintGUI.class
                .getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PrintGUI.class
                .getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PrintGUI.class
                .getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PrintGUI.class
                .getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new PrintGUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel Background;
private javax.swing.JButton Export2ExcelButton;
private javax.swing.JButton Export2Text;
private javax.swing.JTable PhoneBookTable;
private javax.swing.JButton PrintButton;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   
}

回答1:


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

    }

output>>



来源:https://stackoverflow.com/questions/31003828/populate-a-jtable-with-values-from-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!