2013-10-09 57 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

相关问题