How to highlight a node in a JTree???

I am trying to highlight (actually set the Font to Bold) one node of a JTree when an TreeSelectionEvent occurs (valueChanged method). The node to be highlighted can be different than the one selected.
Thanks for your help.
JavaSan

To control the appearance of tree nodes, you need to write a TreeCellRenderer. Check Sun's tutorial on how to use trees (there's a link to it in the API documentation for JTree). The signature of the method you need to implement is this:
public Component getTreeCellRendererComponent(
    JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)so as you can see, you can vary the appearance of the node based on any of the parameters of that method.

Similar Messages

  • How to highlight Tree node with a diff color

    I have created tree node and want to highlight Selected node with a different background color. Any Ideas how can we achieve that? -R

    It's an item on page 4 of the application that the blog example is taken from. The tree query:
    SELECT EMPLOYEE_ID AS ID
         , MANAGER_ID  AS PID
         , CASE
             WHEN EMPLOYEE_ID = :P4_EMPLOYEE_ID THEN
                 '<span style="color:white;background-color:blue;">'||
                 LAST_NAME||
                 '</span>'
             ELSE
                 LAST_NAME
           END AS NAME
         , 'f?p=&APP_ID.:4:'||:SESSION||'::NO::P4_EMPLOYEE_ID:'||EMPLOYEE_ID AS LINK
         , NULL        AS A1
         , NULL        AS A2
      FROM #OWNER#.EMPLOYEESgenerates leaf nodes that link to page 4, setting the value of P4_EMPLOYEE_ID. When page 4 is rendered, P4_EMPLOYEE_ID contains the ID of the clicked node, the page displays details of the employee with this ID, and the case expression in the tree query causes the corresponding display value to be highlighted.
    See the sections Managing Session State Values and Using f?p Syntax to Link Pages in the documentation to understand how to set session state values using URLs.
    http://download.oracle.com/docs/cd/E14373_01/appdev.32/e11838/concept.htm

  • How to select a node in a JTree by name

    I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
    Thanks!

    I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
    So in short, I have the String name of the node that I want to programatically select.
    Thanks!

  • How to highlight a node in a tree?

    i used setSelectionPath() . But it is highlighting the node's icon only(i.e by changing the color to lavender). I'm getting higlighted the node with setSelectionInterval(ind,ind) only. I want that higlighlighting to be with setselectionPath() . How to do?
    Appreciating any help
    Thanks.

    When I do a setSelectionPath the node-text is highlighted, not the icon. Anyways, do a custom treecellrenderer like this:
    public Component getTreeCellRendererComponent(.......) {
    if(selected == true) setBackground(somecolor)
    else setBackground (defaultcolor)
    if that describtion isnt sufficient try search the forum.

  • How to use custom nodes in a JTree without reinventing the wheel?

    Hello,
    Each node contains two JTextAreas in a Box layout and a few JButtons.
    I wish to display these nodes in a JTree.
    Reading the tutorial, it seems I would have to reimplement the TreeModel, TreeCellRenderer/Editor, MutableTreeNode interfaces etc.
    Can I use the DefaultTreeModel, and other standard widgets (great stuff!) to minimize the amount of reimplementation I must do. aka avoid reinventing the wheel? I was thinking of extending my node from the DefaultMutableTreeNode class - however it does not display the nodes with the TextAreas, buttons etc.
    any help appreciated.
    thanks,
    Anil

    was able to fix it over here:
    http://forum.java.sun.com/thread.jspa?messageID=4089777

  • How do I make nodes in my JTree render as JTextPanes ?

    As a newbie to Java, I developed an application which started out by by having a user select a value in a JList and associated information was formatted nicely into a JTextPane (really it is just making some bold/italic/regular font switches).
    I now think it may be more visually appealing to represent the whole thing as a JTree, and the user would just click the +/- to access the associated information.
    So I would like substitute the JTree for the JList, while keep my nicely formatted JTextPane and am a bit stuck. I'd like each item in the JList to be a node and the information is going to be a leaf.
    Searching through the forums and other tutorials it I think I need to create a TreeCellRenderer that uses my JTextPane.
    Aside from advice such as Prior Planning Prevents Poor Performance, can someone give me a gentle kick in the right direction ? Pseudo-code or links would be great !
    Thanks in advance.

    Hi codingMonkey,
    I've looked at both of those (previously) but I've not got enough experience to figure out the coding bits for my application.
    So lets say I wanted to hack the JTextPane example here http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html and put a simple JTree in its place with three nodes and use the provided JTextPane as a text for the leafs.
    I think the important bits (except are addStylesToDocument) are this:
    private JTextPane createTextPane() {
            String[] initString =
                    { "This is an editable JTextPane, ",            //regular
                      "another ",                                   //italic
                      "styled ",                                    //bold
                      "text ",                                      //small
                      "component, ",                                //large
                      "which supports embedded components..." + newline,//regular
                      " " + newline,                                //button
                      "...and embedded icons..." + newline,         //regular
                      " ",                                          //icon
                      newline + "JTextPane is a subclass of JEditorPane that " +
                        "uses a StyledEditorKit and StyledDocument, and provides " +
                        "cover methods for interacting with those objects."
            String[] initStyles =
                    { "regular", "italic", "bold", "small", "large",
                      "regular", "button", "regular", "icon",
                      "regular"
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    I don't really understand the TreeCellRenderer API link you sent and how to link the above JTextPane to the TreeCellRenderer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to get a node  in a Jtree on which right mouse button is clicked

    I am dealing with a situation in which whenever tree component is clicked by right mouse button I am needed to get the tree node on which right mouse button was clicked.

    MouseEvent e = ...
    TreePath path = tree.getPathForLocation(e.getX(), e.getY());
    Object nodeClickedOn = path.getLastPathComponent();Or something along those lines.

  • How to remove a node from  a Jtree?

    I tried giving this to move a node from one parent node to other parent node.
    IconNodeClass userObject = (IconNodeClass)tr.getTransferData(TransferableDataItem.Image_Tree_Node_Flavor);
    IconNodeClass node = (IconNodeClass)path.getLastPathComponent();
    IconNodeClass newNode = new IconNodeClass(userObject);
    DefaultTreeModel model = (DefaultTreeModel)getModel();
    IconNodeClass oldParentNode = (IconNodeClass)userObject.getParent();
    Object oldParent = oldParentNode.getUserObject();
    Object newParent = node.getUserObject();
    if(oldParent.equals(newParent)) {
    model.insertNodeInto(newNode, node, 0);
    if(oldParentNode != null) {
    oldParentNode.remove(newNode);
    model.reload(oldParentNode);
    }

    what happened next ?????

  • 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

  • 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 get total number of nodes in a JTree?

    Hi,
    I am trying to get total number of nodes in a JTree, and cannot find a way to do it.
    The current getRowCount() method returns the number of rows that are currently being displayed.
    Is there a way to do this or I am missing something?
    thanks,

    How many nodes does this tree have?
    import java.awt.EventQueue;
    import javax.swing.*;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.*;
    public class BigTree {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    TreeModel model = new TreeModel() {
                        private String node = "Node!";
                        @Override
                        public void valueForPathChanged(TreePath path,
                                Object newValue) {
                            // not mutable
                        @Override
                        public void removeTreeModelListener(TreeModelListener l) {
                            // not mutable
                        @Override
                        public boolean isLeaf(Object node) {
                            return false;
                        @Override
                        public Object getRoot() {
                            return node;
                        @Override
                        public int getIndexOfChild(Object parent, Object child) {
                            return child == node ? 0 : -1;
                        @Override
                        public int getChildCount(Object parent) {
                            return 1;
                        @Override
                        public Object getChild(Object parent, int index) {
                            return node;
                        @Override
                        public void addTreeModelListener(TreeModelListener l) {
                            // not mutable
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(new JScrollPane(new JTree(model)));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }But for bounded tree model using DefaultMutableTreeNode look at bread/depth/preorder enumeration methods to walk the entire tree. Or look at the source code for those and adapt them to work with the TreeModel interface.

  • How to tap non node area in a JTree

    how can I trap area of a JTree which does not constitute the node rows???

    selPath.getPathForLocation(me.getX(),me.getY())
    this function returns null if there is no rows. you cant track by this.
    Raheel

  • How do I get a dotted line to connect nodes in a JTree?

    I am trying to recreate a Windows Explorer application, does anyone know how they get the dotted lines to connect the nodes in the JTree????

    JTree uses a specific line style to represent the edges between nodes. The default is no edges, but we can set JTree�s lineStyle client property so that each parent node appears connected to each of its child nodes by an angled line:
    myJTree.putClientProperty("JTree.lineStyle", "Angled");
    We can also set this property such that each tree cell is separated by a horizontal line:
    myJTree.putClientProperty("JTree.lineStyle", "Horizontal");
    To disable the line style:
    myJTree.putClientProperty("JTree.lineStyle", "None");
    As with any Swing component, we can also change the UI resource defaults used for all instances of the JTree class. For instance, to change the color of the lines used for rendering the edges between nodes as described above, we can modify the entry in the UI defaults table for this resource as follows:
    UIManager.put("Tree.hash", new ColorUIResource(Color.lightGray))
    Hope this serves your purpose.
    Regards,
    Sachin Shanbhag

Maybe you are looking for

  • Color a row in ALV report

    Hi Freinds, I want to color a particular row based on the condition in ALV report can any one tell me how to do it. Thanx and advance, Line

  • Problem in creating Oracle CLOB thorough JAVA

    HI, I am facing problem in inserting CLOB data through Oracle. My code sends exception at below java code line:- oracle.sql.CLOB newClob = oracle.sql.CLOB.createTemporary(nativeConnection,false, oracle.sql.CLOB.DURATION_SESSION); Exception is::::: ==

  • HT3131 my monitor will not show desktop in closed clamshell?

    When I have my Macbook Pro Open, my monitor is on.  When I close my macbook pro (clamshell closed) my external monitor goes blank.  I bought my macbook pro in 2011.  I run Mountain Lion.  This just started occuring today.  Prior to today, it worked f

  • Preparation for Consolidation using EC-CS

    Dear FI/CO experts, We have a huge chunk of  AR/AP/GL open items with wrong or missing values for trading partner (VBUND), profit center(PRCTR) and partner profit center(PPRCTR) fields. We implemented EC-CS in our organization and need to rectify or

  • Portal Favorites problem

    When i save a KM folder to my Portal Favorites..it seems to work fine... but when i save a link to other portal content like "Content Administration/Portal Content" using the "add to Portal favorites" dropdown from the upper right of the page...it ad