I have recently been working on a Java Swing project and today I get stuck when modifying childrens of a DefaultMutableTreeNode
.
The following SSCCE illustrates the problem:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class Test
{
private static boolean executed = false;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
final DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
final JTree tree = new JTree(root);
tree.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent ev)
{
if (ev.getClickCount() == 2)
{
root.removeAllChildren();
for (String s: get())
{
root.add(new DefaultMutableTreeNode(s));
System.out.println(s + " added");
}
System.out.println();
tree.expandPath(tree.getSelectionPath());
}
}
});
frame.add(tree);
frame.setSize(200,200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
static String[] get()
{
if (!executed)
{
executed = true;
return new String[]{"a","b","c"};
}
else return new String[]{"a","b","c","d"};
}
}
As you see, the first time the get()
method is invoked it returns a 3-element array, and a 4-element one afterwards. When I double-click (actually press) the root node for the first time there should be three children nodes (a, b and c), and the program behaves as expected. When I double-click the root node again I suppose it would have four children nodes. However it doesn't. When you double-click for the second time there are still only three, not four children nodes.
Did I make a mistake? Thanks for help in advance.
you should notify the model about changes use
reload()
methodadd this lines before
expand path
like bellow