Question

I am creating a Jtree with a rootNode and than create another thread that update the root node asynchronously.

It works fantastic if i run this Jtree independently in some JPanel, it was even working at some place in the project, but i was asked to have this Jtree in some new swing Component.

In new Swing Panel, it doesnot populate fully, it only populate the nodes that were inserted (at start for few milliseconds) before the Jtree was rendered on the Screen. Once the Jtree is rendered it doesnt get updated. Now the interesting part i also made a mouse listener on the node so that i can create a new node by right click create node function, and with that new node is created and is added on the Jtree root node.

Important thing to add i was using newThread(){void run}).start() method to create a thread to add node on the Jtree, becuase i never felt the need of SwingUtilities.invokeLater method before. but now if i used SwingUtilities.invokeLater method than the main window also doesnot open it just halts during the startup, i just checked that SwingUtilities.invokeLater also works fine with the old component and ofcourse works fine independently.

And i do call model.nodeStructureChanged(changedNode); after adding the node thats why it was working fine before.

Kindly asist, code is difficult to extract and Jtree code was working fine before, may be some component block the containing widgets to refresh itself async?

EDIT Update to include some code, i am using Temp class as provided by Nick:-

    public BasicGraphEditor(String appTitle, mxGraphComponent component)
{
    // Stores and updates the frame title
    this.appTitle = appTitle;

    // Stores a reference to the graph and creates the command history
    graphComponent = component;
    final mxGraph graph = graphComponent.getGraph();
    undoManager = createUndoManager();

    // Do not change the scale and translation after files have been loaded
    graph.setResetViewOnRootChange(false);

    // Updates the modified flag if the graph model changes
    graph.getModel().addListener(mxEvent.CHANGE, changeTracker);

    // Adds the command history to the model and view
    graph.getModel().addListener(mxEvent.UNDO, undoHandler);
    graph.getView().addListener(mxEvent.UNDO, undoHandler);

    // Keeps the selection in sync with the command history
    mxIEventListener undoHandler = new mxIEventListener()
    {
        @Override
        public void invoke(Object source, mxEventObject evt)
        {
            List<mxUndoableChange> changes = ((mxUndoableEdit) evt
                    .getProperty("edit")).getChanges();
            graph.setSelectionCells(graph
                    .getSelectionCellsForChanges(changes));
        }
    };

    undoManager.addListener(mxEvent.UNDO, undoHandler);
    undoManager.addListener(mxEvent.REDO, undoHandler);

    // Creates the graph outline component
    graphOutline = new mxGraphOutline(graphComponent);

    // Creates the library pane that contains the tabs with the palettes
    libraryPane = new JTabbedPane();

            /////////////////////////////////////////////////
            // Only change i have done here: start
            ////////////////////////////////////////////////
    Temp tempExplorer = new Temp();

    libraryPane.add("new Explorere", tempExplorer);

            /////////////////////////////////////////////////
            // Only change i have done here: End
            ////////////////////////////////////////////////

    // Creates the inner split pane that contains the library with the
    // palettes and the graph outline on the left side of the window
    JSplitPane inner = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            libraryPane, graphOutline);
    inner.setDividerLocation(320);
    inner.setResizeWeight(1);
    inner.setDividerSize(6);
    inner.setBorder(null);

    // Creates the outer split pane that contains the inner split pane and
    // the graph component on the right side of the window
    JSplitPane outer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inner,
            graphComponent);
    outer.setOneTouchExpandable(true);
    outer.setDividerLocation(200);
    outer.setDividerSize(6);
    outer.setBorder(null);

    // Creates the status bar
    statusBar = createStatusBar();

    // Display some useful information about repaint events
    installRepaintListener();

    // Puts everything together
    setLayout(new BorderLayout());
    add(outer, BorderLayout.CENTER);
    add(statusBar, BorderLayout.SOUTH);
    installToolBar();

    // Installs rubberband selection and handling for some special
    // keystrokes such as F2, Control-C, -V, X, A etc.
    installHandlers();
    installListeners();
    updateTitle();
}

The above class is from Jgraph library as https://github.com/jgraph/jgraphx And i am just adding the jtree component like as above, no other changes. please help.

Was it helpful?

Solution

Swing isn't thread safe unless explicitly stated. In the JavaDocs for JTree, it explicitly says this isn't thread safe. If you update it in a thread outside the EDT, there's no guarentee anything will work. So if you want to update a JTree from a different Thread, you need to use SwingUtilities.invokeLater(Runnable run); in order to put the request on the EDT.

I'd recommend having a data structure to store the info of the JTree, and only using the JTree for User Interaction (not data storage).

EDIT

Here's an example of using SwingUtilities.invokeLater() to update a JTree while in the component model. Without you posting any code, this is the best I have to work with. Please try to use this to recreate your problem (add pieces of your code to this example until you have narrowed down what the problem is).

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;

public class Temp extends JPanel{
    JTree tree = new JTree();

    public Temp(){
        JScrollPane jsp = new JScrollPane(tree);

        // Creates the library pane that contains the tabs with the palettes
        JTabbedPane libraryPane = new JTabbedPane();

        libraryPane.add("new Explorere", jsp);

        // Creates the inner split pane that contains the library with the
        // palettes and the graph outline on the left side of the window
        JSplitPane inner = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                libraryPane, new JPanel());
        inner.setDividerLocation(320);
        inner.setResizeWeight(1);
        inner.setDividerSize(6);
        inner.setBorder(null);

        // Creates the outer split pane that contains the inner split pane and
        // the graph component on the right side of the window
        JSplitPane outer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inner,
                new JPanel());
        outer.setOneTouchExpandable(true);
        outer.setDividerLocation(200);
        outer.setDividerSize(6);
        outer.setBorder(null);

        // Puts everything together
        setLayout(new BorderLayout());
        add(outer, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        final Temp temp = new Temp();
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(temp);
                frame.pack();
                frame.setVisible(true);
            }});

        Thread updater = new Thread(temp.new CustomThread());
        updater.start();
    }

    public class CustomThread implements Runnable{

        @Override
        public void run() {
            for(int i = 0; i < 1000; i++){
                updateTree("New Item "+ i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        public void updateTree(final String nodeToAdd){
            SwingUtilities.invokeLater(new Runnable(){

                @Override
                public void run() {
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode(nodeToAdd);
                    model.insertNodeInto(child, root,root.getChildCount());
                    tree.scrollPathToVisible(new TreePath(child.getPath()));
                }});

        }

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top