2013-10-09 43 views
1

我想從文件選擇器中選擇多個文件並將這些值放入JTable。我試過這樣,但JTable上重複相同的值。在打印行中,它會正確打印值。如何將多個文件選擇器的值添加到jtable

JFileChooser fileChooser = new JFileChooser(); 
fileChooser.setMultiSelectionEnabled(true); 
int returnVal = fileChooser.showOpenDialog(fileChooser); 
if (returnVal==JFileChooser.APPROVE_OPTION) { 

    File file[] = fileChooser.getSelectedFiles(); 
    DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); 
    Vector v = new Vector(); 

    for (int i = 0; i < file.length; i++) { 
     String name; 
     String path; 
     long size; 
     name = file[i].getName(); 
     path = file[i].getPath(); 

     System.out.println("name = "+name+" path = "+path); 

      v.add(name); 
      v.add(path); 
      dtm.addRow(v);; 

      } 

    try { 

    } catch (Exception ex) { 
    System.out.println("problem accessing file"+file.getAbsolutePath()); 
    } 
} else { 
    System.out.println("File access cancelled by user."); 
} 

回答

1

使用JButton作爲細胞編輯,如圖here。讓按鈕的事件處理程序調用JFileChooser。更新您的TableModel以反映所選文件。

2

您希望每次都添加一個新的Vector - 您需要將您的Vector移動到您的for循環中。

for (int i = 0; i < file.length; i++) { 
     Vector v = new Vector(); 
     String name; 
     String path; 
     long size; 
     name = file[i].getName(); 
     path = file[i].getPath(); 

     System.out.println("name = "+name+" path = "+path); 
     v.add(name); 
     v.add(path); 
     dtm.addRow(v);; 
     // rest of your code 
+0

它的工作很多感謝名單@ – user2136160

+0

user2136160:您能接受這個答案通過單擊[空對勾(http://meta.stackexchange.com/questions/5234/how-does-accepting-an -answer-work/5235#5235)在左邊。 – trashgod

相關問題