Highlight root node in jtree

When I build my JTree, I have just one single node, the root node. So in order to highlight it, I basically do setSelectionRow(0);, however this is not highlighting the node as if a user clicked it with a mouse, WHEN THE APPLICATION COMES UP.
Once the application comes up, if I click on that node or for that matter any other node, they get highlighted in blue. It's only upon initialization that this doesn't work.
Here's a snippet of the sample code:
tree = new JTree();
tree.setCellRenderer(new RateManagerTreeCellRenderer());
I've also tried the setSelectionPath(TreePath path) method without any success. I think that my Custom TreeCellRenderer could be the culprit. If someone could try to duplicate this problem by using the code below of my RateManagerTreeCellRenderer, I would appreciate it.
public class RateManagerTreeCellRenderer extends DefaultTreeCellRenderer
private static Color oldColor = Color.BLACK;
private static Color newColor = Color.BLUE;
private HashMap iconMap = new HashMap();
public Component getTreeCellRendererComponent(
          JTree tree, Object value,
          boolean selected, boolean expanded,
          boolean leaf, int row,
          boolean hasFocus)
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value;
Object userObject = treeNode.getUserObject();
if (userObject instanceof NameAndID)
NameAndID nameAndID = (NameAndID)userObject;
int count = nameAndID.getItemCount();
if (count > 0 && !selected)
setForeground(newColor);
else if (!selected)
setForeground(oldColor);
this.setToolTipText(((NameAndID)userObject).toString());
String type = nameAndID.getType();
setIcon(type);
return this;
}

Do you mean setting the focus on that node? Or are you talking about some custom painting to put a background behind it? We can't help you much if you don't ask a more specific question with more details about what you're trying to do.

Similar Messages

  • How to disable selection of root node in JTree

    Hi all! Thanks for taking a minute to read my post!
    I am writing a really basic JTree for showing a list of items.
    Here is some of the code:
    /** Create a basic tree **/
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Title");
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree tree = new JTree(treeModel);
    /** Method to return the string of the current highlighted selection **/
    public String getSelectionString()
    DefaultMutableTreeNode node =
    tree.getSelectionPath().getLastPathComponent();
    return (String)node.getUserObject();
    I would like to disable selection of the root node of my JTree.
    Thus, if I make a call to getSelectionString() above, it would return null instead of the string that represents the root label.
    I have read the following forum on disabling various TreePaths and TreeNodes in a JTree:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=224691
    This forum suggests implementing the TreeSelectionListener interface and the TreeSelectionModel class and over-riding the addSelectedPath() methods. I tried this suggestion, and I was able to enable and disable the different children of the Jtree, but the root of the JTree would not disable.
    I suppose that I could just simply remove the visibility of the root node, but I really want to avoid that option if possible.
    Wait --- let me be clear ---- I want to disable the selection of the root node only - still allowing selection of all its children.
    Any suggestions?
    Am I missing something really simple here?
    Did I explain my problem clearly?
    Thanks in advance!
    jewels

    simply try this..
    in the
    public void valueChanged(javax.swing.event.TreeSelectionEvent event);
    method of TreeSelectionListener impelentation get the
    TreePath tp = event.getPath();
    from TreePath get the component and then remove the selection from the treePath if it is the node u were checking/root node in this case
    tree.getSelectionModel().removeSelectionPath(tp);
    Try out....

  • Is it possible to set the root node of JTree by default close???? Pls Help

    Hello frnz,
    I am working on JTreeTable and rt now i am facing a problem , in which i have to keep the root of the JTree by default close,
    So please suggest me to do what for this.

    How about
    JTree.collapseRow(0)

  • JTREE: Custom TreeModel does not update non-root nodes

    I have a JTree that uses a custom TreeModel that wraps over (delegates to) a data class X which keeps track of all its children. The class X maintains its own data structure internally (references to other data objects). It also implements 'equals' and 'hashcode' methods. When the data changes in X, it invokes fireTreeStructureChanged on the TreeModel. (There is a TreeModelListener registered with the TreeModel). This works very well for the root node but not for the other non-root nodes. The JTree correctly calls 'equals' and I can see that equals returns 'false' but for non-root nodes the JTree does not refresh though I can see the underlying data structure has changed.
    I am wondering if I may not have fully & correctly implemented fireTreeStructureChanged as it doesn't seem to do much. Or I may be looking at the wrong place. Any pointers would be appreciated.
    BTW, this question is very similar to one asked years earlier http://forums.sun.com/thread.jspa?threadID=153854 but it didn't help me :(
    Thanks.
    ps: working with jdk1.6.0_06 on WinXP.

    I have a same problem. I got an error "Cannot Update Libray".

  • Set JTree root node

    how do i set the root node in JTree, whereas the root node should not be the parameter in the JTree constructor. is there a methode "set root"
    thanks

    hi,
    ((DefaultTreeModel)yourtree.getModel()).setRoot(aTreeNode);

  • How to highlight node in JTree?

    After the tree has been displayed, I want to highlight the nodes matching some certain keywords. How to implement that? Nothing useful is found in past threads.
    thanks.

    to take a wild guess:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class HighlightTreeNodeTest {
      private final JTree tree       = new JTree();
      private final JTextField field = new JTextField("foo");
      private final JButton button   = new JButton();
      private final MyTreeCellRenderer renderer =
        new MyTreeCellRenderer(tree.getCellRenderer());
      public JComponent makeUI() {
        field.getDocument().addDocumentListener(new DocumentListener() {
          @Override public void insertUpdate(DocumentEvent e) {
            fireDocumentChangeEvent();
          @Override public void removeUpdate(DocumentEvent e) {
            fireDocumentChangeEvent();
          @Override public void changedUpdate(DocumentEvent e) {}
        tree.setCellRenderer(renderer);
        renderer.q = field.getText();
        fireDocumentChangeEvent();
        JPanel p = new JPanel(new BorderLayout(5, 5));
        p.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        p.add(field, BorderLayout.NORTH);
        p.add(new JScrollPane(tree));
        return p;
      private void fireDocumentChangeEvent() {
        String q = field.getText();
        renderer.q = q;
        TreePath root = tree.getPathForRow(0);
        collapseAll(tree, root);
        if (!q.isEmpty()) searchTree(tree, root, q);
        tree.repaint();
      private static void searchTree(JTree tree, TreePath path, String q) {
        TreeNode node = (TreeNode)path.getLastPathComponent();
        if (node==null) return;
        if (node.toString().startsWith(q)) tree.expandPath(path.getParentPath());
        if (!node.isLeaf() && node.getChildCount()>=0) {
          Enumeration e = node.children();
          while (e.hasMoreElements())
            searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
      private static void collapseAll(JTree tree, TreePath parent) {
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        if (!node.isLeaf() && node.getChildCount()>=0) {
          Enumeration e = node.children();
          while (e.hasMoreElements()) {
            TreeNode n = (TreeNode)e.nextElement();
            TreePath path = parent.pathByAddingChild(n);
            collapseAll(tree, path);
        tree.collapsePath(parent);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new HighlightTreeNodeTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      private final TreeCellRenderer renderer;
      public String q;
      public MyTreeCellRenderer(TreeCellRenderer renderer) {
        this.renderer = renderer;
      @Override public Component getTreeCellRendererComponent(
          JTree tree, Object value, boolean isSelected, boolean expanded,
          boolean leaf, int row, boolean hasFocus) {
        JComponent c = (JComponent)renderer.getTreeCellRendererComponent(
            tree, value, isSelected, expanded, leaf, row, hasFocus);
        if (isSelected) {
          c.setOpaque(false);
          c.setForeground(getTextSelectionColor());
        } else {
          c.setOpaque(true);
          if (q!=null && !q.isEmpty() && value.toString().startsWith(q)) {
            c.setForeground(getTextNonSelectionColor());
            c.setBackground(Color.YELLOW);
          } else {
            c.setForeground(getTextNonSelectionColor());
            c.setBackground(getBackgroundNonSelectionColor());
        return c;
    }

  • How to change icon of a node or root node of a JTree

    i have a JTree with a root node, and leaf nodes. i want to change their icons. how can i do this?
    thanks

    Here's a search of the forums with the words 'tree', 'icon' and 'node' in the title
    http://onesearch.sun.com/search/developers/index.jsp?and=jtree+icon+node&nh=10&phr=&qt=&not=&field=title&since=&col=devforums&rf=0&Search.x=28&Search.y=15
    I looked at a couple and #5 seems interesting, but there are quite a few to choose from.

  • How do i get to display the nodes under the root node in a JTree?

    In my JTree there is a root node.This root node has 4 child nodes.Each child node in turn has nodes under it.What i need to do is just display the child nodes under the root node i.e., the four child nodes and keep these child nodes in a collapsed state.How do i go sbout this?

    Please try this:
    tree.expandRow(0);
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            tree.setRootVisible(false);
    });If you want to show the RootHandles:
    tree.setShowsRootHandles(true);If you want to keep nodes in collapsed state (not expandable):
            tel = new TreeWillExpandListener() {
                public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
                    throw new ExpandVetoException( event, "Don't want" );
                public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
            tree.addTreeWillExpandListener(tel);Some reading material:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    http://java.sun.com/docs/books/tutorial/uiswing/events/treewillexpandlistener.html
    Edited by: Andre_Uhres on Nov 14, 2007 5:17 PM
    Edited by: Andre_Uhres on Nov 14, 2007 5:33 PM
    Edited by: Andre_Uhres on Nov 14, 2007 5:39 PM

  • How to create JTree without root node

    Hello;
    I like to create a JTree without root node?
    Any help?
    Thanks!
    --tony                                                                                                                                                                                   

    javadocs JTree,
    setRootVisible
    public void setRootVisible(boolean rootVisible)
    Determines whether or not the root node from the TreeModel is visible.
    Parameters:
    rootVisible - true if the root node of the tree is to be displayedSee Also:
    rootVisible

  • Lining up root node and child nodes in JTree

    I have a JTree that has a root node and n child nodes. There are no sub-levels - it is structured just like AOL instant messenger. What I want to do is have the child node icons line up directly under the root nodes text. For example (if you can read this), where "-" denotes the icon:
    - root
    - child
    - child
    Currently it is something like this:
    - root
    - child
    - child
    I have been messing with the setLeftChildIndent( int ) and setRightChildIndent( int ), but they are not doing much...they seem to not want to only move the leaf nodes but all of the nodes, so its not doing exactly what I want.
    Any ideas? In the meantime I'll be looking more into how exactly those indent mutators work.
    Thanks!

    What you want is to do a setRootVisible(false) on the JTree.
    All your child nodes are then your "root level" folders.
    tree.setRootVisible(true):
    +root
    +--child1
    +--child2
    +--child3
    +----child3a
    +----child3btree.setRootVisible(false):
    +child1
    +child2
    +child3
    +--child3a
    +--child3b

  • How to remove all nodes (except root node)from a Jtree?

    How to remove all nodes (except the root node)from a Jtree?

    Either:
    - remove all children of root.
    - save the root node, throws away the tree model, build a new TreeModel with the saved root, set the new TreeModel in the JTree.
    - implement your own TreeModel, which would support an emptyExceptRoot() method.
    IMHO, using the DefautlTreeModel and DefaultMutableTreeNode does lead to all sorts of small problems when the app evolves, and implementing your own TreeNode and TreeModel is not that hard and much more efficient.

  • JTree no root node

    how do you create a JTree with no root node?
    i just want
    Parent
    --child
    Parent
    --child
    --child                                                                                                                                                                                                   

    i think a tree must always have a root node....but I think what u can do is make that root node not visible...i've seen it done before.
    good luck

  • How to rename node in JTree?(URGENT)

    Hi,all:
    I am facing a renaming problem in JTree. After I rename, the node still remain the old name, Could anybody tell me why and how to solve it?
    The piece of code is as follow:
    JTextField textField = new JTextField();
    newDndTree.setCellEditor(new MyCellEditor(newDndTree,textField));
    newDndTree.setEditable(true);
    class MyCellEditor extends DefaultCellEditor {
    private JTree tree;
    public MyCellEditor(JTree tree, JTextField text) {
    super(text);
    this.tree = tree;
    public boolean isCellEditable(EventObject e) {
    boolean rv = false; // return value
    if(e instanceof MouseEvent) {
    MouseEvent me = (MouseEvent)e;
    if(me.getClickCount() == 3) {
    TreePath path =
    tree.getPathForLocation(me.getX(), me.getY());     
    if(path.getPathCount() == 1) // root node
    return false;
    DefaultMutableTreeNode node =
    (DefaultMutableTreeNode) path.getLastPathComponent();
    Object hitObject=path.getLastPathComponent();
    if(hitObject instanceof TreeNode)
    return (((TreeNode)hitObject).isLeaf());
    return (false);

    Hi,all:
    My problem is it doesn't rename the node, the node remain the old name.
    My piece of code as follow:
    //Set Cell Editor
    newDndTree.setCellEditor(new MyCellEditor());
    //inner class MyCellEditor
    class MyCellEditor extends DefaultCellEditor {   
    public MyCellEditor() {     
    super(new JTextField());
    public boolean isCellEditable(EventObject e) {     
    if(e instanceof MouseEvent) {     
    MouseEvent me = (MouseEvent)e;     
    if(me.getClickCount() == 3) {      
    JTree tree = (JTree)me.getSource();     
    TreePath path = tree.getPathForLocation(me.getX(), me.getY());     
    if(path.getPathCount() == 1) {        
    //System.out.println("Root");     
    return false; // root node     
    DefaultMutableTreeNode node =     
    (DefaultMutableTreeNode) path.getLastPathComponent();     
    Object hitObject=path.getLastPathComponent();     
    if(hitObject instanceof TreeNode) {        
    TreeNode t = (TreeNode)hitObject;     
    boolean b = t.isLeaf();     
    if (b) {          
    //System.out.println("Leaf");     
    return (((TreeNode)hitObject).isLeaf());     
    //else System.out.println("Not Leaf");     
    // System.out.println("Exit");
    return false;
    }

  • Create multiple root in a JTree??????very urgent..pl

    hello
    i have a jtree which takes a defaultMutableTreenode as its parameter.
    My problem is that i have to create multiple root.
    and what i get with this is a single root at the top.
    what is the solution for creating multiple roots in a jtree.
    pl. help its very urgent
    thanx
    hussain

    Hello Hussain,
    I found in the sourcecode of JTree the following constructor which might is be helpful for you:
    * Returns a <code>JTree</code> with each element of the specified
    * <code>Vector</code> as the
    * child of a new root node which is not displayed. By default, the
    * tree defines a leaf node as any node without children.
    * @param value a <code>Vector</code>
    * @return a <code>JTree</code> with the contents of the
    *          <code>Vector</code> as children of the root node
    * @see DefaultTreeModel#asksAllowsChildren
    public JTree(Vector value) {
    this(createTreeModel(value));
    this.setRootVisible(false);
    this.setShowsRootHandles(true);
    Greetings
    Helmut

  • Insert node into JTree with own TreeModel

    Hi,
    I use JTree in combination with my own TreeModel. When a node is removed I use this to inform all listeners:
    actListener.treeStructureChanged(new TreeModelEvent(this, pathToRoot));The above works fine. Now if I insert a node and its' parent is already expanded nothing happens at all! I tried to call actListener.treeStructureChanged(new TreeModelEvent(this, pathToRoot)); and actListener.insertTreeNodes(new TreeModelEvent(this, pathToRoot)); without success!
    As long as the parent is collapsed and a new node is inserted my getChildCount() method in my TreeModel gets called and the freshly added node will be display correctly but whan the node is already expanded nothing happens.
    I've also checked the listeners of my model: one of them is JTree, so it is informed about the insertions but why won't it update its' view? It's especially funny since everything is fine when deleting a node.
    Many thanks for any hints.
    Regards,
    Ren�

    I am struggling with the same problem, and have yet to find a solution, maybe some more suggestions can be made? Here is the situation... I've got a JTree and a custom TreeModel. Now, if I do not expand a node, I can insert and delete from it at will using treeStructureChanged(new TreeModelEvent(this,path))and when I expand the node it will have the correct children. However, once I have expanded the node, all attempts to add or remove children are futile. Even if I un-expand the node, changes will not register in the JTree. I've tried out both suggestions already provided in this thread, but to no avail. Additionally, if I reset the root node, all my changes will appear correctly, however the trees "expanded" state is lost and this is not desireable.
    Anybody have any advice?

Maybe you are looking for

  • How to get a vendor list for a event type in training and events

    Hi i need to get a vendor list for the event type. is there any function module to get the vendor name and vendor no if event type is passed. kindly help me... With regards Rusidar.

  • Am I the only one that wants iTunes to change metadata?

    Is there any way where I can get iTunes match to change my metadata? Most of my songs have inconsistant capilization and spelling errors and stuff like that. Is there a setting to change so itunes will change the metadata to what is listed on the itu

  • HT1414 what to pick? ipod or ipad? i am also tempted by the amazon kindle fire hd.

    Hey, I am very confused. For a present, my relatives asked me to pick whatver i want, and i really want an apple device of my own. What do i pick? i really dont need a phone, i alredy have a samsung galaxy.

  • Adobe RGB vs. sRGB

    In iPhoto 5, when importing photos from my Canon 20D with the color space set to Adobe RBG, JPEGS look washed out. Raw images (.cr2) look fine. If I set the camera to sRGB, both the JPEGS and Raw images look OK - the JPEGS are not washed out. Has thi

  • 3c389 on ti pci1225 cannot bring the interface up!

    I have Solaris 10 x86 (8/04) worrking on my HP Omnibook 4150B Laptop (256MBRAM, HD40GB), every thing is working great, but the network card (3c589c) i can't bring it up, is there any help ??? This is my 3rd try at this place with no previous response