views:

33

answers:

1

I want to make it like when I click a button, it will create a new file. Then the jTree will highlight the new file. Below are my code. Currently I create new file, i will show the new file but no highlight the file.

class FileTreeModel implements TreeModel {
private FileNode root;

public FileTreeModel(String directory) {
    root = new FileNode(directory);
}

public Object getRoot() {
    return root;
}

public Object getChild(Object parent, int index) {
    FileNode parentNode = (FileNode) parent;
    return new FileNode(parentNode, parentNode.listFiles()[index].getName());
}

public int getChildCount(Object parent) {
    FileNode parentNode = (FileNode) parent;
    if (parent == null || !parentNode.isDirectory()
            || parentNode.listFiles() == null) {
        return 0;
    }

    return parentNode.listFiles().length;
}

public boolean isLeaf(Object node) {
    return (getChildCount(node) == 0);
}

public int getIndexOfChild(Object parent, Object child) {
    FileNode parentNode = (FileNode) parent;
    FileNode childNode = (FileNode) child;

    return Arrays.asList(parentNode.list()).indexOf(childNode.getName());
}

public void valueForPathChanged(TreePath path, Object newValue) {

}

public void addTreeModelListener(TreeModelListener l) {
}

public void removeTreeModelListener(TreeModelListener l) {
}

}

class FileNode extends java.io.File {

public FileNode(String directory) {
    super(directory);
}

public FileNode(FileNode parent, String child) {
    super(parent, child);
}

@Override
public String toString() {
    return getName();

}

}

       jTree = new JTree();
        jTree.setBounds(new Rectangle(164, 66, 180, 421));
        jTree.setBackground(SystemColor.inactiveCaptionBorder);
        jTree.setBorder(BorderFactory.createTitledBorder(null, "",
                TitledBorder.LEADING, TitledBorder.TOP, new Font("Arial",
                        Font.BOLD, 12), new Color(0, 0, 0)));
        FileTreeModel model = new FileTreeModel(root);
        jTree.setRootVisible(false);
        jTree.setModel(model);
        expandAll(jTree);

public void expandAll(JTree tree) {

    int row = 0;
    while (row < tree.getRowCount()) {
        tree.expandRow(row);
        row++;
    }
   }
+1  A: 

you can do this by calling JTree.setSelectionPath(TreePath path);

smeg4brains
Hi thanks for you answer, if I know the file name let said NewFile how to know the TreePath?
@newbie123: There's an example here http://stackoverflow.com/questions/2958322
trashgod
The code doesn't not work
afaik you can just do new TreePath(TreeNode node)
smeg4brains
no works as well still not highlighting the new file