2015-06-23 74 views
0

我新的Java和我有這樣填充「的JTable」與價值觀從「.TXT」文件

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     
} 
+0

我剛剛從 更新了 'Vector data; Vector columns;' 至 'Vector data = new Vector(); Vector columns = new Vector();' –

+0

那麼你的問題解決了嗎? –

+0

我剛剛從 更新爲 'Vector data; Vector columns;' 至 'Vector data = new Vector(); 矢量列=新的向量();' 現在的數據則顯示,但問題是我得到 '[0711495765,PK,加米尼,657414589v,科倫坡,0114756199,HP,Weerasigha,657895478v,康提]'在第一個細胞中,在下一個細胞中'[0786160384,PK,Tharindu,912921549v,Colombo]'。 –

回答

0

您需要將您更改爲類似this.you需要,當你閱讀新行,否則包含第一行+第二行+等每次重置向量data = new Vector(); 。並且您也可以撥打dtm.setRowCount(0);以避免空的初始行。而你只需要添加行您的評論的問題[電池含有大量列]是因爲 dtm.addRow(new Object[]{columns, data})使用dtm.addRow(data);,而不是和問題將

代碼

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

    } 

輸出>>

enter image description here

+0

不能安全地將每個行(按行)分別添加到XxxTableModel – mKorbel

+0

試過了。仍然遇到同樣的問題。什麼都不顯示。 –

+0

等待有問題 –