Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7857171
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T20:57:21+00:00 2026-06-02T20:57:21+00:00

I have a custom JTree implementation that implemts convertValueToText . This implementation depends on

  • 0

I have a custom JTree implementation that implemts convertValueToText. This implementation depends on some global state. If the returned string is longer (actually I think wider as in pixels triggers it) than a previously returned string, the text will be truncated and padded with “…”. This is true when the redrawing is caused by (de)selecting the element or a repaint on the tree.

Is it valid to implement convertValueToText in such a way? (I recognize that the tree display will not automatically be updated).

How can I get rid of the “…” and force all elements to be correctly drawn with their current textual value?

Update2:

Appearently I violated Swings rather strict treading policy (http://docs.oracle.com/javase/6/docs/api/javax/swing/package-summary.html). Doing the update with:

        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                for (int row = 0; row < tree.getRowCount(); row++) {
                    ((DefaultTreeModel) tree.getModel())
                            .nodeChanged((TreeNode) tree.getPathForRow(row)
                                    .getLastPathComponent());
                }
            }
        });

appears to work correctly.

Update:

Here is a minimal example:

import java.util.Enumeration;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

public class WeirdTreeFrame extends JFrame {
    public class WeirdTree extends JTree {
        public WeirdTree(TreeNode root) {
            super(root);
        }

        @Override
        public String convertValueToText(Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
        }
    }

    public class WeirdNode implements TreeNode {
        protected WeirdNode parent;
        protected WeirdNode children[];
        protected int dephth;
        protected String name;
        protected String names[] = {"Foo", "Bar", "Ohh"};
        public long superCrazyNumber;

        public WeirdNode(WeirdNode parent, String name) {
            this.parent = parent; 
            this.name = name;
            if (parent != null) {
                dephth = parent.dephth + 1;
            } else {
                dephth = 0;
            }
            if (dephth < 10) {
                children = new WeirdNode[3];
                for (int i = 0; i < 3; i++) {
                    children[i] = new WeirdNode(this, name + names[i]);
                }
            }
        }

        @Override
        public TreeNode getChildAt(int childIndex) {
            if (childIndex >= getChildCount()) return null;
            return children[childIndex];
        }

        @Override
        public int getChildCount() {
            return (children != null) ? children.length : 0;
        }

        @Override
        public TreeNode getParent() {
            return parent;
        }

        @Override
        public int getIndex(TreeNode node) {
            for (int i = 0; i < children.length; i++) {
                if (children[i] == node) return i;
            }
            throw new RuntimeException();
        }

        @Override
        public boolean getAllowsChildren() {
            return true;
        }

        @Override
        public boolean isLeaf() {
            return getChildCount() == 0;
        }

        @Override
        public Enumeration children() {
            return new Enumeration<TreeNode>() {
                int nextIdx = 0;
                @Override
                public boolean hasMoreElements() {
                    return nextIdx < getChildCount();
                }

                @Override
                public TreeNode nextElement() {
                    return getChildAt(nextIdx++);
                }
            };
        }

        @Override
        public String toString() {
            return "[" + dephth + "]" + name + "@" + superCrazyNumber;
        }
    }

    public WeirdNode root;
    private WeirdTree tree;

    public WeirdTreeFrame() {
        root = new WeirdNode(null, "Blubb");
        tree = new WeirdTree(root);
        add(tree);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setVisible(true);
    }

    public void update() {
        for (int row = 0; row < tree.getRowCount(); row++) {
            ((DefaultTreeModel) tree.getModel()).nodeChanged((TreeNode)tree.getPathForRow(row).getLastPathComponent());
        }
    }


    public static void main(String[] args) {
        WeirdTreeFrame frame = new WeirdTreeFrame();
        Random rnd = new Random(41);

        for (long i = 0; ; i++) {
            for (WeirdNode node = frame.root; node != null; node = (WeirdNode)node.getChildAt(rnd.nextInt(3))) {
                node.superCrazyNumber++;
            }
            if (i % 1e7 == 0) {
                System.out.println("Update: " + i);
                frame.update();
            }
        }
    }
}

With the update() method I tried to fire the appropriate events to make sure all visible nodes are updated correctly. As you can see some computation is happening in parallel and perioically during the computation I want to update the tree labels (NOT the structure).

The issue with the update() method is that some nodes are labled completely wrong as you can see in the attached picture (should be “[0]…” for root node, “[n]..”for nth level)

mixed up node labels

I assume this is some race condition.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T20:57:23+00:00Added an answer on June 2, 2026 at 8:57 pm

    This probably means your are updating the tree without telling it you changed something so when it redraws it just redraws it without recalculating the layout. You have to call DefaultTreeModel.nodeChanged(node) from the model to notify JTree you actually modified something then it will handle recalculating the size of the node. Or use the proper TreeModelListener interface call to notify the Tree something has changed. If you do that it will relayout that node properly.

    If you are properly notifying the tree JLabel is redrawing itself, but it is not performing layout again to calculate how much space it needs for the new string. If you revalidate() it (as opposed to repaint()) it should perform layout again and it will calculate its preferred size again based on the new string and resize itself to surround the entire string.

    The section in the main() method that manipulates the tree then calls update is violating the swing thread rule because when WeirdFrame is constructed it is realized by the call setVisible(). That means you can’t touch it or any model being used to draw from from any thread except the Swing Event Dispatcher thread. It doesn’t have anything to do with whether you implement TreeNode or not.

    The easiest fix to this is to defer it back to the Event Dispatch thread. like so:

    public void update( final WeirdNode node, final long nextSuperCrazyNumber ) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                node.superCrazyNumber = nextSuperCrazyNumber;
                ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
            }
        });
    }
    
    public static void main(String[] args) {
        WeirdTreeFrame frame = new WeirdTreeFrame();
        Random rnd = new Random(41);
    
        for (long i = 0; ; i++) {
            for (WeirdNode node = frame.root; node != null; node  =(WeirdNode)node.getChildAt(rnd.nextInt(3))) {
                long superCrazyNumber = node.superCrazyNumber;
                frame.update( node, superCrazyNumber++ );
            }
        }
    }
    

    Now notice how the main thread is running unfettered, but it isn’t directly manipulating the data contained in the WeirdNode. Remember WeirdNode’s toString() method is called to render a string to display so it’s being called on the SwingThread. If you write to WeirdNode.superCrazyNumber on from another thread you are violating the threading rule. The main thread getting a copy doing some calculation to it, then posting the update back to the Swing Thread using SwingUtilities.invokeLater() NOT invokeAndWait(). You don’t need invokeAndWait except is very limited situations, and it has to potential to cause lock ups so its best to just avoid it. Your UI doesn’t have to reflect the model at every second it just has to eventually reflect it and so invokeLater is your friend. The key thing here is I’m not doing a write operation on the main thread as the code before, and I certainly can call update on the individual nodes without having to resort to shotgun updates.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have custom exceptions in my django project that look like this: class CustomFooError(Exception):
I have custom assembly that is loaded on runtime. at this point i have
I have custom groupViews that need to change state when they are expanded and
I have custom SPlist with some fields that I'd like to bind to a
I have a custom swing component that is implemented similar to a JTree. It
I have custom classes that I currently instantiate within App.xaml as resources. I want
I have custom event that has several different subscribers who will all use the
I have custom gallery. Gallery represents items that are frame layout. There are one
I have custom component that I can place in my layout file (XML) for
I'm using a custom TreeModel for a JTree. I have an issue when I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.