I know there are a lot of similar questions to be found on Google, but I just seem to not be able to make it work somehow:
I have a JTree (called Project) and this tree has different Nodes (Folder or Table). I can add Folders and Tables to the JTree and they display after reloading the model. Now what I want to do is, once I have added a new Folder or Table to the Tree this one should be selected and expanded, but I cant get it to work.
I will try to just pick the important pieces of the code:
public void openProject() {
final JFileChooser select = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Project Files (.prj)", "prj");
select.addChoosableFileFilter(filter);
int returnVal = select.showOpenDialog(null);
String path = select.getSelectedFile().getPath();
String extention = path.substring(path.length() - 4);
if (returnVal == JFileChooser.APPROVE_OPTION
&& extention.equalsIgnoreCase(".prj")) {
try {
XMLDecoder d = new XMLDecoder(new BufferedInputStream(
new FileInputStream(path)));
setModel((TreeModel) d.readObject());
d.close();
// restore status
List<TreeNode[]> expanded = (List<TreeNode[]>) d.readObject();
for (int i = expanded.size() - 1; i > -1; i--) {
TreeNode[] ar = expanded.get(i);
expandPath(new TreePath(ar));
}
projectPath = path;
} catch (FileNotFoundException ex) {
}
setRootVisible(true);
reloadTree();
root = (DefaultMutableTreeNode) getModel().getRoot();
}
}
This piece will open up an existing Project (similar function for a new Project), define the root, set the model and reloads the tree.
If I now try:
public void addTable(){
Table table = new Table();
table.setUserObject("Table1");
try{
DefaultMutableTreeNode last = (DefaultMutableTreeNode) getLastSelectedPathComponent();
last.add(table);
}catch(Exception e){
root.add(table);
}
TreePath path = new TreePath(table.getPath());
setSelectionPath(path);
expandPath(path);
reloadTree();
}
public void addFolder(){
Folder folder = new Folder();
folder.setUserObject("Folder1");
try{
DefaultMutableTreeNode last = (DefaultMutableTreeNode) getLastSelectedPathComponent();
last.add(folder);
}catch(Exception e){
root.add(folder);
}
TreePath path = new TreePath(folder.getPath());
setSelectionPath(path);
expandPath(path);
reloadTree();
}
It will add the node, but does not expand the path or select the newly created node. If I manually select the node, I can use this as the parent with the getLastSelectedPathComponent.
Where did I get the concept wrong? I guess I do have a pretty simple mistake in there, but I am struggling here.