10

I used a JTree in my GUI and added it to a JFrame. When I want to update it and change it's nodes in another part of my program (while program is running, as an action performed) I try to add new nodes, or remove nodes to it; But my interface doesn't change. Please suggest me a solution.

regards

sajad
  • 2,094
  • 11
  • 32
  • 52

3 Answers3

16

In addition to the insertNodeInto suggestion you can also use:

DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
root.add(new DefaultMutableTreeNode("another_child"));
model.reload(root);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    So thank you for your worthy answer ! Every time I want to update my tree I use this method. – sajad Sep 30 '10 at 12:42
  • 3
    This will work but is a "brute force" approach when dealing with large trees. For example, if I were to loop and add 1000 nodes to a tree already containing 50,000 items this would be very inefficient. – Adamski Oct 05 '10 at 16:30
  • 1
    In the wild how often does the tree get large enough that this becomes slow enough to worry about? – Kevin Kostlan Aug 16 '15 at 22:53
2

You need to ensure that after updating your model you instruct it to fire an event to cause any registered listeners to be notified of the event. One of the listeners will be the JTree and upon receiving the event it will repaint.

For example, DefaultTreeModel contains the methods:

nodeChanged nodesChanged nodeStructureChanged nodesWereInserted nodesWereRemoved

Also, as with all Swing programming you need to ensure you are updating your model on the Event Dispatch Thread.

Adamski
  • 54,009
  • 15
  • 113
  • 152
  • 1
    You don't have to fire these events off yourself. All you have to do is update the model by calling the `insertNodeInto` method, for example, and let the model take care of firing events to the TreeModelListeners. – dogbane Sep 29 '10 at 13:28
  • 1
    Good point, although in some cases it would be better to manage it yourself. For example, if I wanted to add 1000 child nodes I would not wish to fire 1000 "nodes were added" events. – Adamski Sep 29 '10 at 14:13
  • Thank you Sir! But these methods you mentioned are private and couldn't be accessed. – sajad Sep 30 '10 at 12:43
  • You're absolutely right! I've changed my answer to reflect the correct public methods you should be calling. – Adamski Oct 05 '10 at 16:27
-1

Do you mean the GUI aspect just isn't showing your change? You should probably look int repaint() and revalidate().

Here's a good description of when to call which one.

Community
  • 1
  • 1
Bryan
  • 2,068
  • 2
  • 15
  • 18
  • Yes calling this methods are necessary. – sajad Sep 30 '10 at 12:44
  • 4
    -1, No repaint() and revalidate() are not necessary. When you udpate the model the model is responsible for notifying the view of the change so the tree can repaint itself. – camickr Sep 30 '10 at 14:42