填充“JTable”#39;来自' .txt'的值文件

时间:2015-06-23 13:14:43

标签: java swing file-io jtable stringtokenizer

我是java的新手,我有一个像这样的文本文件

0786160384|P. K.|Tharindu|912921549v|Colombo|
0711495765|P. K.|Gamini|657414589v|Colombo|
0114756199|H. P.|Weerasigha|657895478v|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();
    }

} 

有人可以帮帮我吗?

下面是我的整个代码

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 个答案:

答案 0 :(得分:0)

你需要将你改成这样的东西。每当你读新行时你需要重置向量data = new Vector();,否则它包含第一行+第二行+依此类推。你也可以调用{{1避免空的初始行。并且你只需要添加行,你的评论问题[单元格包含很多列]是因为 dtm.setRowCount(0);使用dtm.addRow(new Object[]{columns, data})代替,问题将得到解决

dtm.addRow(data);

输出&GT;&GT;

enter image description here