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

Similar Messages

  • 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

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

  • How to select node in JTree without firing event?

    I have got standard situation. JTree in the left panel, and several edit boxes in right panel. Certainly, I have TreeSelectionListener, which on every tree node selection shows corresponding model values in edit boxes.
    I'd like to implement next logic:
    1. Something was changed in any edit box in right panel. Model has been changed.
    2. User clicks on different node in tree.
    3. Dialog "Message was not saved. Save?" with Yes/No/Cancel buttons are shown.
    Yes/No buttons are easy to handle.
    Question is about Cancel. I'd like on Cancel button left all edit boxes in their present state (do not restore values from saved model) and select back node, which wasn't saved.
    Problem is next. If I select node by setSelectionPath or smth like that, but... JTree fires event and my listener receives onTreeItemSelected back, which checks that node wasn't saved and ......
    Who does have any idea, or have done similar tasks? How can I select node and do not allow tree fire event this time?
    Thanks in advance.

    First, as soon as the model changes (when editing any
    combo box) some flag will be set. Now the logic which
    updates the combo boxes will do it only on a change of
    the current node and (this is new) if the flag wasn't
    set. You should have some flag anyway because somehow
    you must determine when to show the dialog, shouldn't
    you?Yes, I have got this logic implemented. But it's only the half :)
    I know exactly when my model has been changed, but if it was changed, i'd like to ask user what to do next - svae/loose changes/cancel
    And on cancel i'd like to select last edited tree node and do not get event from tree at that moment.
    >
    Second way, prevent selecting a new node if that flag
    has been set. You could do this by subclassing
    DefaultTreeSelectionModel and overriding some methods
    (setSelectionPath() et al).Ok. I'll investigate this.
    >
    MichaelThanks.

  • How to add nodes to JTree???

    Hi ,
    i'm developing an application using the NetBeans 6.0. I was trying to add the Nodes on the "JMenuItem" Click event.
    I know how to add the customized code to the JTree, but while adding following code to the JMenuItem's Click, does'nt work
    Code :
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt)
                       DefaultMutableTreeNode dm =new DefaultMutableTreeNode("Root Element");
                       dm.add(new DefaultMutableTreeNode("Child Node"));
                       Treeview=new javax.swing.JTree(dm);
    }        Please help me out where i should write the code so that it will add the nodes to the JTree on JMenuItem's Click.
    Thanks in Advance
    - Hitesh

    Read the tutorial: [Dynamically Changing a Tree|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#dynamic]

  • 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

  • How to highlight/indicate particular tree Node in Tree UI element

    Hi All
    Can anybody let us know how to highlight/indicate specific node in a tree struture.
    currently i am able to display the tree struture with all the nodes & elements but it is always tasking firstnode as highlighted one or indicated one.
    if i want to highlight specific node in a tree struture...what was the procedure or any sample code then it would be great help to us.
    Thanks
    Trisha rani

    Hi Krishna
    Thanks for your reply
    I displayed the tree structure and i want to highlight specific parent node/child element , what was the sample code??
    for example my tree was displayed in the below struture and at the runtime specific child node i wanted to be highlighted i want to make selectable particular nodeType......
    Can you pls send sample codee code??
    my requirement
    A
    A1
       A2
       A3
    B
    B1      
       B2
       B3
       B4
       B5     
    now i want to make selectable or highlighted B4,B5 etc  or A2,A3 at runtime.
    The other guy who replied for this thread it is working for Parent nodes to make highlighted  like it is working for parent nodes which is have child nodes. i am able to hightlight at runtime for Nodes A,B etc .
    Now i want to highlight or make selected one for B4,A3 etc, pls provide sample code??
    it  would be great help to us
    Thanks
    Trisha Rani

  • How to dynamically add Nodes to JTree?

    How to add nodes to a Jtree by getting the information into a specific file
    For example, in JList:
    DefaultListModel workgroups;
    workgroups = new DefaultListModel();
    List<String> workgroupsList = new ArrayList<String>();
    workgroupsList = ParserUtils.getWorkgroupList(ParserUtils.getConfigPath() + "\\.workgroup.properties");
    if (!workgroupsList.isEmpty()){
         for (String workgroup : workgroupsList){
              workgroups.addElement(workgroup.toString().trim());
    workgroupList = new JList(workgroups); //adds the list workgroupsThe output of this will be a JList displaying the list of workgroups per line. The list could be found in a file name "workgroup.properties"
    Question is, is it possible to adapt this same method in JTree. The information per line will serve as one node in the tree. For example, I have 3 workgroups in the list, there will also be 3 nodes to be found in the tree.
    Any suggestions?
    THanks.

    There's a huge JTree example in the Swing tutorial. It's a bit of a beast to use.

  • 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 :-)

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

  • How to highlight the messages in the WDA?

    hi experts,
                     Iam new to Webdynpro.i just want to know how to highlight the texts displayed . like BOLD,italic etc and also colors.
    Regards,
    murthy.

    I dont think you have it via standard message area. Probably you can have a TextView UI element and use the properties Design and semanticColor to achieve this. If you have a contextNode , thats mapped to the texview and message manager writing text to this node. Solution should work.
    Greetings
    Prashant

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

  • 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

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

Maybe you are looking for

  • Connection to a nokia 6288

    Hello, This is not exactly a question about iSync but there are other nokia-problems here, so I give it a go: I just bought a nokia 6288, but I can't connect it to my iMac G5 (no bluetooth) with the usb-cable , (with bluetooth to a mpb works fine). W

  • Show / Hide fields in Crystal 11

    Post Author: djhc50 CA Forum: Formula I am in need of some help in the "if-Then-Else" world of Crystal 11, and being a newbie, am largely unfamiliar with the syntax.  Basically, I have a situation where I need to display the current date and time on

  • Photo Slideshow editing

    I have loaded all of my photos into iMovie with the intention of creating a slideshow. I have music chosen and I have ordered the photos in the way I would like them. So now the slideshow plays, but in rough format. However, the one thing I can't see

  • Can't Get To Front Row...

    Help! I know my Remote is working because pushing play/pause will start/stop an iTunes song. But when I press Menu, it will not bring up Front Row. I checked my mouse/keyboard shortcuts as well, and it's set to bring up Front Row with Command + Escap

  • READER XI and "NOT RESPONDING" ERROR!!!

    I just downloaded Reader XI and now I can not open up ANY pdf documents!  I keep getting the "Not Responding" Error Message!  Please help!!!