Highlighting nodes in JTree

Hey guys please help me for this.
I want to generate a Tree. In which after some action a few nodes are selected.
Now i want to highlight those selected node in the Tree. Is it possible ??
Is anyone have any clue how to do that.
Thanks in advance

well, even I'm facing this issue in my application but i did a small workaround. I am sure there should be a better way of achieving this, which i hope someone will post in this thread.
Use Html tags in displaying the highlighted node:
DefaultMutableTreeNode node = new DefaultMutableTreeNode ("<html><b>node1</b></html>");
Pankaj

Similar Messages

  • 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;
    }

  • Highlighting nodes in a JTree

    Hi,
    I'd like to know how I can produce the efect of highlighting nodes in a JTree when the mouse moves over the JTree.
    Thanks

    You say to get the mouseevent coordinates with a mouse
    listener, but which component should be the caller of
    the methos addMouseListener?
    If I choose the jtree, I can't get the 'mouseevent
    coordinates' each time the mouse moves over a node,
    because the methods mouseEntered and mouseExited are
    invoked just once (when the mouse enter inside the
    jtree's area (mouseEntered), and when the mouse gets
    out the jtree's area(mouseExited)), so I can't change
    the boolean field to true for nodes which have the
    mouse over.just use mouseMoved of the MouseMotionListener.
    however, i have my doubts that you will have a lot of fun with the suggested method (correct though it is).
    at least make sure you only call the repaint method if the mouse moved into a new node. you might want to try the the nodeChanged method, that way you don't repaint the whole tree every time.
    thomas

  • Help needed with finding node in JTree

    Hi,
    In my application i will be entering some string data in a text box for search criteria.
    When I click on search, I will get data from database which will be shown as a JTree.
    This Jtree will have some nodes in which, node with string entered in the search text box exists.
    I need to focus on this node and I have only a string to find this node.
    How can I do this?How can I find a node in JTree using string value?
    Is there any alternate option by which I can achive my need?
    Please suggest.
    Thanks.

    @OP: please assign your dukes.
    @Andre_Uhres: if you don't get rewarded in the next couple of days, please let me know here to get at least one duke for your effort.
    Bye.

  • Problem inserting new node into JTree with depthFirstEnumeration()

    Hello,
    I'm currently trying to use depthFirstEnumeration() to add and delete nodes for a simple JTree. I've written a method to handle this, but it keeps coming back with an exception saying that 'new child is an ancestor'.
    All I'm trying to do is add and delete nodes from a JTree using add and remove buttons within a swing program. When a user adds the new node the JTree needs to be updated with new labels in sequential order dependent upon a depthFirst traversal of the JTree.
    My current code for the add button is as follows,
    public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            Enumeration e = rootNode.depthFirstEnumeration();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    while (e.hasMoreElements()) {
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)e.nextElement();
                     // treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    //System.out.print(newNode.getUserObject() + "" + newNodeSuffix++);
                    String label = "Node"+i;
                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    i++;
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);
                    //System.out.println();
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        } As you can see in the above code, I've tested the incrementing of the new nodes in a System.out.print() statement and they appear to be incrementing correctly. I just can't see how to correctly output the labels for the nodes.
    Any help and advice always appreciated.

    This is about the 5th posting on the same question. Here is the link to the last posting so you can see what has already been suggested so you don't waste your time making the same suggestion.
    http://forum.java.sun.com/thread.jspa?threadID=704980
    The OP doesn't seem to understand that nodes don't just rename themselves and that renderers will only display the text of the current node. If you want the text displayed to changed, then you need to change the text associated with each node, which means iterating through the entire tree to update each node with new text. Then again, maybe I don't understand the question, but the OP keeps posting the same question without any additional information.

  • Drag and Drop nodes in JTree

    Is there a way to drap and drop JTree nodes without resorting to hacks? http://www.javaworld.com/javatips/jw-javatip97.html outlines a hack to get drag and drop working but it is kinda old. I am wondering whether there is a now a way to do this in Swing. http://weblogs.java.net/blog/shan_man/archive/2006/01/first_class_dra.html outlines a seemingly promising way but when I tried it it still wouldn't let me drag JTree nodes. (btw, if you are going to try it, you must replace TransferHandler.TransferInfo with TransferHandler.TransferSupport. It has apprently been renamed.)

    I have implemented drag and drop of nodes in JTree they same way it is explained in JavaWorld link that you mentioned, I customized it for my application and it worked great.

  • Highlight node in tree in apex 4

    Hello!
    The tree has nodes. Node name can include the number in brackets, for example "Messages (1)". Requires such nodes in the tree is highlighted in red, regardless of whether a node is selected or not. At the same time a tree node can be at different levels, not necessarily at the root or leaf.
    I made javascript, but it does not work correctly, API tree is not very clear.
    The script highlights only the first level and all children, and that is not true.
    treeData = window [tree.attr ('id'). replace (/ ^ tree (\ d +)$/, 'l $ 1Data')] [0]. children;
    for (var i = 0; i <treeData.length; i + +)
    try {
    if (/ \ S + \ (\ d + \) $ /. test (treeData . data.title))
    {apex.jQuery ('li [id =' + treeData [i]. attributes.id + '] a'). css ('color', 'red'). css ('font-weight', 'bold'); }} catch (err) {}
    for (var j = 0; j <treeData [i]. children.length; j + +)
    try {if (/ \ S + \ (\ d + \) $ /. test (treeData [i]. children [j]. data.title)
    {apex.jQuery ('li [id =' + treeData [i]. children [j]. attributes.id + '] a'). css ('color', 'red'). css ('font-weight', 'bold');}} catch (err) {}
    Help please!
    [Not correctly work: http://files.mail.ru/FHON5H|http://files.mail.ru/FHON5H]

    It can be used static ID for node
    In sql:
    case when msg_count>0 then 'TreeRed_' || rownum
    else 'TreeBlack_' || rownum
    end as value,
    In js:
    $('[id^="TreeRed_"]').children('a').css('color', 'red').css('font-weight', 'bold');
    How can I highlight node without renaming ID, couse I need ID for links?

  • Wordwrap nodes in jtree

    Anyone know how we can do wordwrap of nodes in jtree?
    Please help...
    Thanks.

    Any example on this? what html code should I use? The simplest possible, eg
    yourNode.setText("<html>" + yourNodeText + "</html>");Most JComponents can render this html string and produce a good result. But if you wanna get a little more complex and use styles and other web things, then do as said, (two posts above) and use a JEditorPane specifically for cell renderer
    ICE

  • How to set the default tree node in JTree?

    I want to set a default tree node in JTree when start the program,
    what is the method or the function to call?
    Thanks~

    If you by "default" mean "selected", then you can use one of the setSelectionXXX methods in the JTree API.
    If you by "default" mean something else, never mind this post :-)

  • Setting custom color for selected node in JTree?

    Hi,
    i want to set my own color for selected node in JTree. i don't want to set for all the nodes...how to set Color for Selected node using TreeCellRender class?
    Thanks
    Mani

    I assume you are not setting a custom tree cell renderer...
    javax.swing.JTree theTree = ...;
    java.awt.Color newBGColor = ...;
    ((javax.swing.tree.DefaultTreeCellRenderer)theTree.getCellRenderer())
        .setBackgroundSelectionColor(newColor);

  • Add node to JTree

    I have an already populated JTree. At Runtime I add one or more node to JTree, using something like
    parentNode.add(newNode)....
    If I call a repaint method, the new node isn't visible, I have to reload model using
    DefaultTreeModel dtm = ((DefaultTreeModel)myTree.getModel());
    TreeNode rootNode = (TreeNode) dtm.getRoot();
    dtm.reload(rootNode);
    Unfortunately this method cause the lost of focus on the currently selected node and the collapse of all JTree around its root node; If I change an existing node (for example changing its text or icon) I must reload the model too!!!
    Does exist an other more "soft" method to change the aspect of a JTree without reload the entire model?

    You must use or implement the
        public void valueForPathChanged(javax.swing.tree.TreePath path,java.lang.Object newNode) {
            Object[]    p = path.getPath();
            Object[]    pp = p;
            //insert node here
            int[] ci = new int[] {index};
            Object[] cc = new Object[] {node};
            fireTreeNodesChanged(this, pp, ci, cc);
            fireTreeStructureChanged(this, pp, ci, cc);
        }from the TreeModel. To fire the last two is essensial.
    I implemented a GP in JAVA so i had the same problem wehn i started.

  • JTree de-highlight node

    I have a JTree with DefaultMutableTreeNode-s
    I am using a SINGLE_SELECTION_MODE model
    When I use the mouse to select a node in the JTree, it automatically highlights that node. What should I use if I want to be able to use the mouse to de-select the node and remove the highlight?
    -andrew

    CTRL-click the node to de-select it.

  • 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.

  • How to search a child node in JTree

    Hi I am new to swings..
    My requirement is I have a Jsplit pane.
    I have search button with a text box in one and Jree in another pane.
    When I enter a string and hit Search button...It need to search the tree and expand that node highlight it.
    can anyone help in getting this done.

    public void actionPerformed(ActionEvent e)
      DefaultTreeModel m_model = new DefaultTreeModel(entityRoot);
      DefaultMutableTreeNode node = searchNode(m_searchText.getText());
      JTree m_tree = new JTree(m_model);
      TreePath root = m_tree.getPathForRow(0);
      searchTree(m_tree, root, m_searchText.getText());
    private void searchTree(JTree tree, TreePath path, String q)
    TreeNode node = (TreeNode)path.getLastPathComponent();
    if(node==null) return;
    if(node.toString().startsWith(q))
       tree.setScrollsOnExpand(true);
       tree.setSelectionPath(path);
    if(!node.isLeaf() && node.getChildCount()>=0)
       Enumeration e = node.children();
       while(e.hasMoreElements())
       searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
    }Edited by: EJP on 27/06/2011 09:53: added {noformat}{noformat} tags. Please use them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to get correct node in JTree with DISCONTIGUOUS_TREE_SELECTION mode?

    The following code creats a JTree with DISCONTIGUOUS_TREE_SELECTION mode. When select a single node, the node's name is printed correctly as expected. However, in Window environment, after select one node, if holding the ctrl key and select a different node, the program still prints out the name of the first selected node although both nodes are highlighted. Can some one tell me how to get the name of the second (i.e. the last) selected node printed?
    Thank you very much!
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.io.*;
    public class TestTree extends JFrame {
    JTree tree;
    public TestTree() {
    super();
    setBounds(0,0,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tree = new JTree();
    getContentPane().add(tree);
    TreeSelectionModel model = new DefaultTreeSelectionModel();
    model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setSelectionModel(model);
    tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    Object obj = tree.getLastSelectedPathComponent();
    System.out.println(obj.toString());
    public static void main(String [] args) {
    TestTree test = new TestTree();
    test.show();

    Hi!
    Try this, maybe it's what you want?
    /Smedman
    public void valueChanged(TreeSelectionEvent e)
        TreePath[] paths = tree.getSelectionPaths();
        for (int i = 0; i < paths.length; i++)
            System.out.println(paths.getLastPathComponent());

Maybe you are looking for

  • How do i remove my credit card from apple store

    When i trt to download an app it tells me my security code is wrong. How do i remove my credit card from my billing info?

  • Error while executing Adobe forms

    Hi all, I need a small help regarding SAP Adobe Forms. I have created one adobe form but when i activate it, i get the following error: SOAP Framework Error: SOAP Runtime Exception: CSoapExceptionTransport: HTTP send failed with exception communicati

  • Hierarchy VIewer - Card only on Leaf nodes

    I am using version 11.1.2.3.0. Is there a way to show a Card only on the leaf nodes of the Hierarchy VIewer? I have information that only applies to the nodes on the very bottom of the tree. Thanks in advance.

  • Can't preview podcast (doesn't play)

    We just uploaded our podcasts to iTunes 2 days ago.  All the files are there, but when you click on the small play button to preview them nothing happens.  If I click on "View In iTunes" they play fine.  Any suggestions?  Thanks.

  • PS CS4 Error: Could not build preview because of a disk error

    I have been using this version of Photoshop without any problems for about two years, and then I upgraded to OS X Lion last week and now I get a disk error when I try to save a file.  The message says "Photoshop could not build preview because of a d