I’m learning to JTrees and Java.
Constructive suggestions and feedback are very welcome.
I think I am missing some understanding of JTrees and after 5 hours Googling, and testing I’m stuck. I’ve simplified the code as much as possible.
public void actionPerformed(ActionEvent event) {
MyNode selNode = (MyNode) m_tree.getLastSelectedPathComponent();
if (selNode != null) {
MyNode newNode = new MyNode("New Node");
model.insertNodeInto(newNode, selNode,
selNode.getChildCount());
MyNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
m_tree.scrollPathToVisible(path);
m_tree.setSelectionPath(path);
// ******* The next line throws the exception shown below. ****
m_tree.startEditingAtPath(path);
}
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTreeUI.startEditing(BasicTreeUI.java:2059)
at javax.swing.plaf.basic.BasicTreeUI.startEditingAtPath(BasicTreeUI.java:601)
at javax.swing.JTree.startEditingAtPath(JTree.java:2349)
at ItemCreator.ItemCreator$1.actionPerformed(ItemCreator.java:74)
Code – My Simple Mutable JTree
1) When adding a new node into the JTree the code throws Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
2) Any general constructive feedback very welcome.
Kind regards
The problem is not the startEditingPath, but the incorrect model implementation. Basically its fails to notify its listeners on changes, consequently the ui has no chance to update its internals to include the added node.
The model fails in
It’s not entirely trivial and the java doc slightly (to put it mildly) confusing – that’s why SwingX has a well-tested utility class TreeModelSupport which takes over the burden. It can be used standalone, or as a blue-print of how-to do it.
In your custom model, some relevant changes (incomplete, the other modification methods must be fixed accordingly, as must the remove listener):