Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic JTree and SwingUtilities.invokeLater() does nothing

To create my dynamic JTree, I was reading the tutorial about Dynamic JTrees on this website in chapter "4.2 OutlineNode.java"

Now I have implemented it and recognize that loading the data in the GUI thread takes long and is ugly as well. Therefore I added a thread which expands the children and then adds the TreeNode element to the tree.

private void getChildNodes() {
    areChildrenDefined = true;
    Thread t = new Thread(new Runnable()
    {
        @Override
        public void run() {
        System.out.println("Expand");
            final List<DECTTreeNode> listNodes = new ArrayList<DECTTreeNode>();
            if (castNode().canExpand())
            {
                for(DECTNode crt : castNode().getChildren())
                {   
                    DECTTreeNode treeNode = new DECTTreeNode(crt);
                    listNodes.add(treeNode);
                }

                try {
                    SwingUtilities.invokeAndWait(new Runnable()
                    {
                        @Override
                        public void run() {
                            System.out.println(listNodes.size());
                            for (DECTTreeNode crt : listNodes)
                            {
                                add(crt); // <==== Adds the node to the JTree
                            }
                        }

                    });
                    //}).run();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

    });
    t.start();
}

Without the thread it works without problems. If I add the thread and put the add-calls into a SwingUtilities.invokeAndWait(...), the children seem to be expanded, but they're not visible in the tree.

I've already tried revalidate() and repaint() on the tree - without any effect.

Any idea how to make these elements visible?

Thank you in advance.

like image 460
Atmocreations Avatar asked Mar 29 '26 17:03

Atmocreations


1 Answers

Check that your add() method fires the correct TreeModelEvent

like image 153
Walter Laan Avatar answered Apr 01 '26 08:04

Walter Laan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!