Problems with adding nodes to JTree
Hello!
I have this code for creating a JTree.
import java.io.*;
import java.awt.Dimension;
import java.awt.datatransfer.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import com.torpare.sbnext.objects.*;
publicclass TomasTreeextends JScrollPane{
private JTree tree;
private DefaultMutableTreeNode rootNode;
private DataFlavor fileFlavor;
private List<File> filesToAdd;
private Config config = Config.getInstance();
public TomasTree(String rootNodeText){
super();
rootNode =new DefaultMutableTreeNode(rootNodeText);
tree =new JTree(rootNode);
fileFlavor = DataFlavor.javaFileListFlavor;
this.tree.setTransferHandler(new TransferHandler(){
publicboolean importData(JComponent c, Transferable t){
if (!canImport(tree, t.getTransferDataFlavors())){
returnfalse;
}
try{
if (hasFileFlavor(t.getTransferDataFlavors())){
filesToAdd = (List)t.getTransferData(fileFlavor);
javax.swing.SwingUtilities.invokeLater(new Runnable(){
publicvoid run(){
config.appendAllowableDir(filesToAdd);
createTree(rootNode,filesToAdd);
tree.expandRow(0);
tree.repaint();
}
});
returntrue;
}
}catch (UnsupportedFlavorException ufe){
System.out.println("importData: unsupported data flavor");
}catch (IOException ieo){
System.out.println("importData: I/O exception");
}
returnfalse;
}
publicboolean canImport(JComponent c, DataFlavor[] flavors){
if (hasFileFlavor(flavors)){returntrue;}
returnfalse;
}
privateboolean hasFileFlavor(DataFlavor[] flavors){
for (int i = 0; i < flavors.length; i++){
if (fileFlavor.equals(flavors[i])){
returntrue;
}
}
returnfalse;
}
});
this.setViewportView(tree);
}
publicvoid createTree(DefaultMutableTreeNode topNode, List<File> files){
for(File file : files){
List<File> tempList =new LinkedList<File>();
DefaultMutableTreeNode tempNode =new DefaultMutableTreeNode(file.getName());
topNode.add(tempNode);
File[] tempFileList = file.listFiles();
for(File f : tempFileList){
if(f.isDirectory()){
tempList.add(f);
}
}
createTree(tempNode,tempList);
}
}
// Setters
publicvoid setRootVisible(Boolean rootVisible){
this.tree.setRootVisible(rootVisible);
}
}
when using this with drag and drop everything works like it should. I can drag a folder on to the JTree from Windows Explorer and all subfolders adds to the tree. So what's the problem you ask? Let me tell you :)
If I drag one more folder on to the JTree nothing happens, they get added to the List but not to the JTree. So it's probably my createTree() method that's poorly written. Can anyone help me?

