2010-06-15 30 views
1

我想使它像當我點擊一個按鈕時,它會創建一個新文件。然後jTree將突出顯示新文件。以下是我的代碼。目前我創建新文件,我將顯示新文件但不突出顯示文件。JTree創建新文件使其選中

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

可以通過調用JTree.setSelectionPath(TreePath path)做到這一點;

+0

嗨,謝謝你的回答,如果我知道文件名讓我們說NewFile如何知道TreePath? – user236501 2010-06-15 15:04:04

+0

@ newbie123:這裏有一個例子http://stackoverflow.com/questions/2958322 – trashgod 2010-06-15 16:12:54

+0

該代碼不工作 – user236501 2010-06-15 17:10:20