JTree Node Icons

Ok i know how to set a icon for all nodes in a JTree but my problem is setting incons for certain nodes. I am trying to Create a UML Training Tool for my degree and i have major trouble here. I can change the icons for all but all i want to do is change them for individual nodes, for example a different icon for an actor to a use case, please please can someone help this beginner.

You need to subclass DefaultTreeCellRenderer and override the getTreeCellRendererComponent method, like:
class CustomRenderer extends DefaultTreeCellRenderer {
  public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, sel,expanded, leaf, row, hasFocus);      
    if (whatever) setIcon(myIcon);
}                 Then set the cell renderer for your tree:
myTree.setCellRenderer(new CustomRenderer());

Similar Messages

  • JTree node icon adnd leaf icons

    Need Help.......
    Need to change icon in the root node and leaf ; but they must be different each other . Trying to use a renderer but change every leaf with same icon .same happend to nodes.
    Thanks a lot

    have you gone through this
    [tree display|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display]
    and also try searching the forum there are lot more similar post.

  • How to get the icon type of a JTree node, very urgent

    hi,
    i need to get the type of a JTree node but don't know how. this is quite an emergency. please help. thank you all.
    -joey

    there are several icons defined in the DefaultTreeCellRenderer class, such as closedIcon, leafIcon, openIcon. i was wondering if there is any way to get the icon type of a node. thanks for your reply.
    -joey

  • Parse and display xml doc when click on JTree node?

    Ok so here is the code that I have now. You will have to make alot of html files to run the program, but they can be empty for now. What you can do is just put the same exact html file to be displayed in each node element. for example.
    DefaultMutableTreeNode n1_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));could be changed to
    DefaultMutableTreeNode n1_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "status.html"));And just keep adding the status.html page to each one of the nodes.
    anyway.
    For now when I click on the node, the html file is displayed in the JScrollPane rPane = new JScrollPane(htmlPane); and the htmlPane is a JEditorPane
    what I need it to do.
    When I click on the JTree node. I would like to go out to an xml file, parse the information in it, and display it to the pane.
    I will need to later, be able to add, edit, or delete information on the xml through the pane later.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.accessibility.*;
    import javax.swing.UIManager;
    import javax.swing.JComponent;
    import javax.swing.JEditorPane;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.ImageIcon;
    import java.net.URL;
    import java.io.IOException;
    import java.awt.Dimension;
    * @author orozcom
    public class Example extends JFrame implements TreeSelectionListener
        private JEditorPane htmlPane;
        private URL helpURL;
        private static boolean DEBUG = false;
        private JTree tree;
        public Example()
            super("Example");
            setSize(1200,900);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JMenuBar jmb = new JMenuBar();
            JMenu fileMenu = new JMenu("File");
            JMenuItem openItem = new JMenuItem("Open");
            JMenuItem saveItem = new JMenuItem("Save");
            JMenuItem exitItem = new JMenuItem("Exit");
            exitItem.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    System.exit(0);
            fileMenu.add(openItem);
            fileMenu.add(saveItem);
            fileMenu.add(new JSeparator());
            fileMenu.add(exitItem);
            jmb.add(fileMenu);
            setJMenuBar(jmb);
            //  **************** start JTree ******************//       
            JPanel lPane =new JPanel();       
            lPane.setLayout(new BorderLayout());
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(new ModuleInfo("Devices","splashScreen.html"));
            DefaultMutableTreeNode branch1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Module 1", "module1.html"));
            DefaultMutableTreeNode branch2 =
                    new DefaultMutableTreeNode(new ModuleInfo("Module 2", "module2.html"));
            //DefaultMutableTreeNode branch3 =
                    //new DefaultMutableTreeNode(new ModuleInfo("Module 3", "module3.html"));
            //adding to the topmost node
            top.add(branch1);
            top.add(branch2);
            //top.add(branch3);
             *          BRANCH 1           *
            //adding to the First branch
            DefaultMutableTreeNode node1_b1
                    =new DefaultMutableTreeNode(new ModuleInfo("Status", "status.html"));
            //branch1.add(node1_b1);
                DefaultMutableTreeNode n1_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
                DefaultMutableTreeNode n2_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
                DefaultMutableTreeNode n3_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Chassis", "chassis.html"));
                DefaultMutableTreeNode n4_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Resources", "resources.html"));
                node1_b1.add(n1_node1_b1);
                node1_b1.add(n2_node1_b1);
                node1_b1.add(n3_node1_b1);
                node1_b1.add(n4_node1_b1);    
            DefaultMutableTreeNode node2_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Project Editor", "projedit.html"));
            DefaultMutableTreeNode node3_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Project Manager", "projmngt.html"));
            DefaultMutableTreeNode node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Administration", "administration.html"));
            DefaultMutableTreeNode n1_node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
            DefaultMutableTreeNode n2_node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
            DefaultMutableTreeNode n3_node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Users", "users.html"));
            node4_b1.add(n1_node4_b1);
            node4_b1.add(n2_node4_b1);
            node4_b1.add(n3_node4_b1);
            DefaultMutableTreeNode node5_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Logging", "logging.html"));
            branch1.add(node1_b1);
            branch1.add(node2_b1);
            branch1.add(node3_b1);
            branch1.add(node4_b1);
            branch1.add(node5_b1);
             *          BRANCH 2           *
            //adding to the Second branch
            DefaultMutableTreeNode node1_b2 =
                    new DefaultMutableTreeNode(new ModuleInfo("Status", "status.html"));
                DefaultMutableTreeNode n1_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
                DefaultMutableTreeNode n2_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
                DefaultMutableTreeNode n3_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Chassis", "chassis.html"));
                DefaultMutableTreeNode n4_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Resources", "resources.html"));
                node1_b2.add(n1_node1_b2);
                node1_b2.add(n2_node1_b2);
                node1_b2.add(n3_node1_b2);
                node1_b2.add(n4_node1_b2);
            DefaultMutableTreeNode node2_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Project Editor", "projedit.html"));
            DefaultMutableTreeNode node3_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Project Manager", "projmngt.html"));
            DefaultMutableTreeNode node4_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Administration", "administration.html"));
                DefaultMutableTreeNode n1_node4_b2=
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
                DefaultMutableTreeNode n2_node4_b2=
                        new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
                DefaultMutableTreeNode n3_node4_b2=
                        new DefaultMutableTreeNode(new ModuleInfo("Users", "users.html"));
                node4_b2.add(n1_node4_b2);
                node4_b2.add(n2_node4_b2);
                node4_b2.add(n3_node4_b2);
            DefaultMutableTreeNode node5_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Logging", "logging.html"));
            branch2.add(node1_b2);
            branch2.add(node2_b2);
            branch2.add(node3_b2);
            branch2.add(node4_b2);
            branch2.add(node5_b2);
             *          BRANCH 3           *
            //adding to the Third branch
            DefaultMutableTreeNode node1_b3=new DefaultMutableTreeNode("Status");
            DefaultMutableTreeNode n1_node1_b3=new DefaultMutableTreeNode("Device");
            DefaultMutableTreeNode n2_node1_b3=new DefaultMutableTreeNode("Network");
            DefaultMutableTreeNode n3_node1_b3=new DefaultMutableTreeNode("Chassis");
            DefaultMutableTreeNode n4_node1_b3=new DefaultMutableTreeNode("Resources");
            node1_b3.add(n1_node1_b3);
            node1_b3.add(n2_node1_b3);
            node1_b3.add(n3_node1_b3);
            node1_b3.add(n4_node1_b3);
            DefaultMutableTreeNode node2_b3=new DefaultMutableTreeNode("Project Editor");
            DefaultMutableTreeNode node3_b3=new DefaultMutableTreeNode("Project Manager");
            DefaultMutableTreeNode node4_b3=new DefaultMutableTreeNode("Administration");
            DefaultMutableTreeNode n1_node4_b3=new DefaultMutableTreeNode("Device");
            DefaultMutableTreeNode n2_node4_b3=new DefaultMutableTreeNode("Network");
            DefaultMutableTreeNode n3_node4_b3=new DefaultMutableTreeNode("Users");
            node4_b3.add(n1_node4_b3);
            node4_b3.add(n2_node4_b3);
            node4_b3.add(n3_node4_b3);
            DefaultMutableTreeNode node5_b3=new DefaultMutableTreeNode("Logging");
            branch3.add(node1_b3);
            branch3.add(node2_b3);
            branch3.add(node3_b3);
            branch3.add(node4_b3);
            branch3.add(node5_b3);
            tree=new JTree(top,true);
            //tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
            //Set the icon for leaf nodes.       
            ImageIcon deviceIcon = createImageIcon("/device.gif");       
            if (deviceIcon != null)
                DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                renderer.setLeafIcon(deviceIcon);
                tree.setCellRenderer(renderer);
            else
                System.err.println("Leaf icon missing; using default.");
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
            //Create the scroll pane and add the tree to it.
            //JScrollPane treeView = new JScrollPane(tree);
            tree.setToolTipText(" and ");
            lPane.add(tree);
            getContentPane().add(lPane);
            //  ****************  end  JTree  ******************//
            htmlPane = new JEditorPane();
            htmlPane.setEditable(false);       
            initHelp();
            JScrollPane rPane = new JScrollPane(htmlPane);
            JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, lPane, rPane);
            jsp.setDividerLocation(180);
            getContentPane().add(jsp, BorderLayout.CENTER);
            JPanel bPane = new JPanel();
            JButton okButton = new JButton("Ok");
            JButton applyButton = new JButton("Apply");
            JButton clearButton = new JButton("Clear");
            bPane.add(okButton);
            bPane.add(applyButton);
            bPane.add(clearButton);
            getContentPane().add(bPane, BorderLayout.SOUTH);
            setVisible(true);
        /** Required by TreeSelectionListener interface. */
        public void valueChanged(TreeSelectionEvent e)
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            tree.getLastSelectedPathComponent();
            if (node == null) return;
            Object nodeInfo = node.getUserObject();
            if (node.isLeaf())
                ModuleInfo module = (ModuleInfo)nodeInfo;
                displayURL(module.moduleURL);
                if (DEBUG)
                    System.out.print(module.moduleURL + ":  \n    ");
            else
                displayURL(helpURL);
            if (DEBUG)
                System.out.println(nodeInfo.toString());
        private class ModuleInfo
            public String deviceName;
            public URL moduleURL;
            public ModuleInfo(String device, String filename)
                deviceName = device;
                moduleURL = (URL)Example.class.getResource("/" + filename);
                if (moduleURL == null)
                    System.err.println("Couldn't find file: "
                            + filename);
            public String toString()
                return deviceName;
        private void initHelp()
            String s = "YFDemoHelp.html";
            helpURL = Example.class.getResource("/" + s);
            if (helpURL == null)
                System.err.println("Couldn't open help file: " + s);
            else if (DEBUG)
                System.out.println("Help URL is " + helpURL);
            displayURL(helpURL);
        private void displayURL(URL url)
            try
                if (url != null)
                    htmlPane.setPage(url);
                else
                { //null url
                    htmlPane.setText("File Not Found");
                    if (DEBUG)
                        System.out.println("Attempted to display a null URL.");
            catch (IOException e)
                System.err.println("Attempted to read a bad URL: " + url);
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path)
            java.net.URL imgURL = Example.class.getResource(path);
            if (imgURL != null)
                return new ImageIcon(imgURL);
            else
                System.err.println("Couldn't find file: " + path);
                return null;
        public static void main(String args[])
            new Example();
            //new AssistiveExample();
    }Thanks orozcom

    yes i can at the time of MIRO u can see both
    go in SU01 for and user
    in Parameters enter IVFIDISPLAY in Parameter ID and X in Paramater Value
    thus for that user u will be able to c Invoice number and accounting number after saving MIRo
    u will get message like
    Invoice document 5105608893 was posted ( Accountng Documnt: 5100000000 )
    hope this helps

  • Changing Certain Node Icons

    I can't seem to figure out how to change certain node icons in a JTree due to a 3 letter string. For example 2 nodes one saying "Intro" the other say "Edit - SEC" - the one with SEC has a different icon to "Intro"
    MyRenderer class, here the code which is used to check the string of the node......
    if(leaf && isSecuredFile(value)) {
    setLeafIcon(leafSecuredIcon);
    setToolTipText("This file is Secured Access Only");
    else {
    setToolTipText(null);
    return this;
    protected boolean isSecuredFile(Object value) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
    NodeRecord nodeInfo = (NodeRecord)(node.getUserObject());
    String nodeTitle = nodeInfo.NodeRecord;
    if(nodeTitle.indexOf("SEC") >= 0) {
    return true;
    return false;
    }// MyRenderer class
    I tried the above piece of code, and it compiles with no errors but when I try to run the applet it comes up not initialised with the following....
    java.lang.NoClassDefFoundError: MyRenderer
    at firstPanel.<init>(firstPanel.java:99)
    at JNavigator.jInit(JNavigator.java:55)
    at JNavigator.init(JNavigator.java:40)
    at sun.applet.AppletPanel.run(AppletPanel.java:344)
    at java.lang.Thread.run(Thread.java:484)
    However if I take out this code it works fine but I need to be able to assign different icons depending on the node title string. Therefore I need help.

    here's the whole class, if thats any help...
    public class MyRenderer extends DefaultTreeCellRenderer {
    ImageIcon leafIcon;
    ImageIcon leafSecuredIcon;
    public MyRenderer() {
    leafIcon = new ImageIcon("Leaf.gif");
    leafSecuredIcon = new ImageIcon("LeafSecured.gif");
    public Component getTreeCellRendererComponent(JTree tree, Object val, boolean sel, boolean expand, boolean leaf, int row, boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, val, sel, expand, leaf, row, hasFocus);
    // sets Icons
    setLeafIcon(leafIcon);
    setClosedIcon(new ImageIcon("Folder95C.gif"));
    setOpenIcon(new ImageIcon("Folder95O.gif"));
    // set Expansion icons to + -
    ComponentUI treeUI = tree.getUI();
    if(treeUI instanceof BasicTreeUI) {
    ((BasicTreeUI)treeUI).setExpandedIcon(new ImageIcon("minus.gif"));
    ((BasicTreeUI)treeUI).setCollapsedIcon(new ImageIcon("plus.gif"));
    // decides who icon to use
    if(leaf && isSecuredFile(value)) {
    setLeafIcon(leafSecuredIcon);
    setToolTipText("This file is Secured Access Only");
    else {
    setToolTipText(null);
    return this;
    protected boolean isSecuredFile(Object value) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
    NodeRecord nodeInfo = (NodeRecord)(node.getUserObject());
    String nodeTitle = nodeInfo.NodeRecord;
    if(nodeTitle.indexOf("DOM") >= 0) {
    return true;
    return false;
    }

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • PopupMenu on Jtree nodes Please [b]Help me][/b]

    how can I set my JpopupMenu to work on Jtree nodes and not on the tree?

    how can I set my JpopupMenu to work on Jtree nodes
    and not on the tree?Could you elaborate? Are you asking that popup events are ignored if the mouse click is not actually on the rendered area of a node or are you asking something else?

  • How to sort Jtree node?

    Now, I want to sort tree node by increasing.
    for example there are three child node:
    [20 -40][
    10 - 20]
    [30- 60].
    they are added to JTree node by different order.but are shown in increasingorder.
    like this:
    [10 - 20]
    [20 -40][
    [30- 60].
    how to control tree node.

    Implement the Comparable interface in t he userobject class and possibly the toString(0 as well.
    Ex.
    public class UserObject implements java.lang.Comparable{
    public int compareTo(Object obj) throws ClassCastException
    public String toString()

  • Jtree node refuses to collapse upon clicking handle; makeVisible() was used

    Hello,
    While creating a new node and inserting as a leaf in the JTree, I use tree.makeVisible(newTreePath) to expand the new node and make visible. (Using expandPath() will not expand if a leaf was added).
    However now the jtree node refuses to collapse upon clicking the node handle.
    How do I get it to not insist on staying open - be able to collapse manually?
    thanks,
    Anil

    This is the JNI forum. I don't believe your post fits.
    then
    can I correctly assume that any class that
    "implements Cloneable" will handle making either a
    "shallow" or "deep" ... or even "semi-shallow" clone,
    respective to the class context .. right?
    It probably does something. The implementor might not have implemented anything though. And you have no idea what they implemented.
    No idea about your other question.
    You might want to think carefully about why you are cloning though.

  • Multiline text in a jtree node

    i'm not able to add the multiline text in a jtree node. i've checked the data in both the cases before adding into the tree and after adding into the tree. itz getting the data in the proper format. but while displaying inside the tree itz taking into the single line.
    kindly help me to get the data in a multi line format in the jtree.
    thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.text.*;
    public class DynamicTreeDemo extends JPanel {
    public static String transactionName=null;
    String p1Name=null;
       public static String duration=null;
        public static final String NEWLINE = System.getProperty("line.separator");
    static String[] arrCorrelatorId={"110","122","129","132","130","136","111","109","131","124","127",null};
    static String[] arrParcorrelatorId={"108","110","122","129","122","130","108","108","109","121","121"};
    static String[] arrtransactionName={"FINT3","FINT17","FINT20","FINT52","FINT21","FINT18","FINT4","FINT3"," FINT31","FINT19","FINT51"};
    public static MutableTreeNode node;
    public static DefaultTreeModel model;
    public static TreePath path;
    public static JTree tree;
    static String[] nodeName={"FINT3_108","FINT17_110","FINT20_122","FINT52_129","FINT21_122","FINT18_110","FINT4_108","FINT3_108"," FINT31_109","FINT19_121","FINT51_121",null};
    public DynamicTreeDemo(JFrame frame) {
    final DynamicTree treePanel = new DynamicTree(transactionName);
    populateTree(treePanel);
    JTextField name = new JTextField(20);
    setLayout(new BorderLayout());
    treePanel.setPreferredSize(new Dimension(300, 150));
    add(treePanel, BorderLayout.CENTER);
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(10,50));
    add(panel, BorderLayout.EAST);
    public DefaultMutableTreeNode newObj(String parent){
    DefaultMutableTreeNode pname= new DefaultMutableTreeNode(parent);
    return pname;
    public void populateTree(DynamicTree treePanel)
         String p3;
         DefaultMutableTreeNode p2,nNode, p1;
         int ind=0, i=0,k=0, len=0, m=0;
         boolean flag= false;
         String desc;
         while(nodeName[m]!=null)
         p3 = nodeName[m];
         ind = p3.indexOf("_");
         p3 = p3.substring(0, ind);
           desc=NEWLINE +"hi"+NEWLINE+"how r u";
         if(arrParcorrelatorId[m].equals(arrParcorrelatorId[0]))
                   treePanel.addObject(null, p3,desc);
         else{
              int loopcount=0;
              for(int j=0;nodeName[j]!=null;j++)
                        if(arrParcorrelatorId[m].equals(arrParcorrelatorId[j]))
                             for(int p=0;nodeName[p]!=null;p++)
                                       if(arrCorrelatorId[p].equals(arrParcorrelatorId[j]))
                                            p1=newObj(arrtransactionName[p]);
                                            System.out.println("parent:"+p1);
                                            System.out.println("child:"+p3);
                                            treePanel.addObject(p1, p3,desc);
                                            break;
                        break;
              m++;
    public static void showNodes(String corrId)
         transactionName="FINT3";
    public void DynamicDisplayNode(String corrId){
    JFrame frame = new JFrame("DynamicTreeDemo");
    showNodes(corrId);
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridLayout(1,1));
    contentPane.add(new DynamicTreeDemo(frame));
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args)
    JFrame frame1=null;
    DynamicTreeDemo demo= new DynamicTreeDemo(frame1);
    demo.DynamicDisplayNode("108");
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.Enumeration;
    import java.util.StringTokenizer;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.border.Border;
    import javax.swing.border.LineBorder;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.*;
    public class DynamicTree extends JPanel  {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        protected DefaultTreeCellRenderer linksRenderer;
        public static final String NEWLINE = System.getProperty("line.separator");
        public DynamicTree(String appName) {
             rootNode = new DefaultMutableTreeNode(appName);
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            tree.setEditable(false);
            tree.setShowsRootHandles(true);
            tree.setBackground(Color.white);
            tree.setCellRenderer(new DefaultTreeCellRenderer()
                 public Component getTreeCellRendererComponent(JTree pTree,
                     Object pValue, boolean pIsSelected, boolean pIsExpanded,
                     boolean pIsLeaf, int pRow, boolean pHasFocus)
                       DefaultMutableTreeNode node = (DefaultMutableTreeNode)pValue;
                       JLabel lbl = (JLabel)super.getTreeCellRendererComponent(pTree, pValue, pIsSelected,pIsExpanded, pIsLeaf, pRow, pHasFocus);
                      lbl.setBorder(new LineBorder(Color.RED,1));
                 /* Component c =  super.getTreeCellRendererComponent(pTree, pValue, pIsSelected,
                         pIsExpanded, pIsLeaf, pRow, pHasFocus);
                           if (node.isRoot())
                                          c.setForeground(Color.red);
                          else if (node.getChildCount() > 0)
                                    c.setForeground(Color.blue);
                           else if (pIsLeaf)
                                    c.setForeground(Color.black);//new Color(0x736AFF));*/
                           setBackgroundNonSelectionColor(Color.white);
                           JPanel p = new JPanel();
                           p.setBackground(tree.getBackground());
                           Dimension d = lbl.getPreferredSize();
                           p.setPreferredSize(new Dimension(d.width, d.height));
                           p.add(lbl);
                           tree.setRowHeight(30);
                  return (p);
            JScrollPane scrollPane = new JScrollPane(tree);
            setLayout(new GridLayout(1,0));
            add(scrollPane);
        public void addObject(DefaultMutableTreeNode parent,Object child,String desc)
            child=child+desc;
            //System.out.println("child"+child);
                DefaultMutableTreeNode     parent1;
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
              if (parent == null)
                          parent = rootNode;
              else
                   String parentName = (String)parent.getUserObject();
                   String tok;
                   Enumeration e=null;
                   e=(Enumeration) rootNode.breadthFirstEnumeration();
                   int breakloop=0;
                   parent = rootNode.getLastLeaf();
                    while (e.hasMoreElements() ) {
                        if(parent!= null)
                             //System.out.println("parent.toString():"+parent.toString());
                             tok=parent.toString();
                             StringTokenizer st = new StringTokenizer(tok);
                             parent1=newObj(st.nextToken());
                             if(parent1.getUserObject().equals(parentName))
                                       breakloop=1;
                                       break;
                             parent= parent.getPreviousNode();
                   if(breakloop==0)
                        parent = rootNode.getLastLeaf();
              System.out.println("parent.toString():"+parent.toString());
              System.out.println("childNode"+childNode.toString());
              parent.add(childNode);
    public DefaultMutableTreeNode newObj(String parent){
          DefaultMutableTreeNode pname= new DefaultMutableTreeNode(parent);
              return pname;
    class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
            public void treeNodesInserted(TreeModelEvent e) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
    }

    Here is a simple example.
    import java.awt.BorderLayout;
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class MultiLineTreeDemo extends JFrame {
         private JTree tree;
         public static void main( String[] args ) throws Exception {
              SwingUtilities.invokeLater( new Runnable() {
                   public void run() { new MultiLineTreeDemo(); }
         public MultiLineTreeDemo() {
              super( "MultiLineTreeDemo" );
              setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              DefaultMutableTreeNode root = new DefaultMutableTreeNode( "<html>This is<p>the root node.</html>" );
              DefaultMutableTreeNode node = new DefaultMutableTreeNode( "<html>This is<p>a child node.<html>" );
              root.add( node );
              tree = new JTree( root );
              setLayout( new BorderLayout() );
              JScrollPane scrollPane = new JScrollPane( tree );
              add( scrollPane, BorderLayout.CENTER );
              setSize( 200, 200 );
              setVisible( true );
    }

  • Set different color for one JTree node

    hello,
    I managed to find how to set a color for Jtree nodes but the problem is that with my method all the nodes will b the same color whereas i'm looking to have nodes of different color depending on the situation.
    the method for setting all Jtree nodes the same color(other than black):
    tree.setCellRenderer(
    new DefaultTreeCellRenderer() {
       public Color getTextNonSelectionColor() {
         return Color.lightGray; } });I WANT TO CHOSSE EACH COLOR FOR EACH NODE
    help plz
    thanks

    You need to implement TreeCellRenderer interface
    public Component getTreeCellRendererComponent(JTree tree,
                                                  Object value,
                                                  boolean sel,
                                                  boolean expanded,
                                                  boolean leaf,
                                                  int row,
                                                  boolean hasFocus)You can know which node is rendering by check value argument. Please read DefaultTreeCellRenderer's code.

  • Apex 4 Tree node icon inconsistency ( 4.0.2.00.06 = 4.0.2.00.07)

    <font color="#2C5197">
    <li>If I assign a value to the tree icon column in Apex 4 ( 4.0.2.00.06) , _it is rendered as the node(ins) element's classname_ ( unless it has the "/" character in it,then it becomes the inline background-image property , for example "/add" )
    <li>While in Apex 4( 4.0.2.00.07) , it is always rendered as the background image and I can't make it render as the classname (apex.oracle.com is also on 4.0.2.00.07 and shows the same behaviour as mentioned) .
    </font>
    I have a tree region in apex 4.0(4.0.2.00.06) which has node icons defined conditionally using the SQL query's icon column
    As as example, the code below as Tree Definition (example here)
    select case when connect_by_isleaf = 1 then 0
                when level = 1             then 1
                else                           -1
           end as status,
           level,
           "ENAME" as title,
           case
             when mod(level,2) = 1 THEN 'add'
             else 'delete'
           END as icon,
           "EMPNO" as value,
           'Drill Down to '||ENAME as tooltip,
           'f?p='||:APP_ID||':1:'||:APP_SESSION as link
    from emp_check
    start with "MGR" is null
    connect by prior "EMPNO" = "MGR"
    order siblings by "ENAME"This renders the tree as with *node icons having a class of "add" or "delete"_ in apex 4.0.2.00.06.
    &lt;ins style=&quot;background-image: url(&amp;quot;add&amp;quot;);&quot;&gt;&amp;nbsp;&lt;/ins&gt;On another instance which is on 4.0.2.00.07, the same tree is rendered with the tree's node having a background-image URL as the "add" or "delete"
    &lt;ins class=&quot;add&quot;&gt;&amp;nbsp;&lt;/ins&gt;The Bug Fix list from the Patch Notes ( 5.2 Bugs Fixed in the 4.0.2.00.07 Patch Set ) mentions in Bug Number:9893260 that +"APP_IMAGES and WORKSPACE_IMAGES used in tree region must be preceded by host URL"+.
    Is it possible that as a result of this bug-fix, any value specified for the icon column is being rendered as the background-image ?
    Can someone confirm whether this behavior is expected or is this is a case which has been overlooked in the bug-fix or just another bug ?

    Hi Vee,
    To respond to your question "+Can someone confirm whether this behavior is expected or is this is a case which has been overlooked in the bug-fix or just another bug ?+", the behaviour you see is expected. We now always create a background-image-url style. The fix for bug 9893260, which you referred to in your initial post, was incorporated in our 4.0.1 patch set, as listed under the section "5.1 Bugs Fixed in the 4.0.1.00.03 Patch Set" in the 4.0.2 Patch Set Notes - http://www.oracle.com/technetwork/developer-tools/apex/application-express/402-patch-189110.html. Therefore, I'm surprised that you're seeing different behaviour between 4.0.2.00.06 and 4.0.2.00.07. I'm not aware of any tree-related changes made between those two versions, so I'll investigate that further....but as I said, the behaviour you are seeing with 4.0.2.00.07 is expected.
    Regards,
    Hilary

  • How to add custom ADF Tree Node icon

    Hi All,
    i am using below code in style sheet to set the tree node icon,
    af|tree::node-icon:nodetype-collapsed
    but i don't have any idea how to add getnodetype() method in the node class, (I am using Jdeveloper 11.1.1.2.0). please suggest me the steps to achive it.
    Thanks,
    Mahesh

    i did as you suggested, but i am not getting any image, below is my source
    <nodeDefinition DefName="com.mahesh.SSCExplorer.model.ROview.OrdrHdrVO"
    Name="OrdrHdr20"
    TargetIterator="${bindings.OrdrHdr2Iterator}"
    ClosedIcon="/Nuvola_filesystems_folder.png"
    OpenIcon="/Nuvola_filesystems_folder.png"
    Icon="/Nuvola_filesystems_folder.png">
    please suggest is there any other settings i need to do.
    Thanks,
    Mahesh

  • Hierarchical Tree Node icon ?

    Hi
    How to create a icon on Hierarchical tree
    Regards
    Shahzaib

    Thanks for your reply and i am sorry for not clear my developer version
    My developer version is 6I
    Database express addition
    Well i write the trigger when tree node activate
    :parameter.current_emp := ftree.get_tree_node_property(find_item('Block28.Tree8'),
                                                          :system.trigger_node,
                                                          ftree.node_value);
    DECLARE
    htree         ITEM;
    current_node  FTREE.NODE;
    find_node     FTREE.NODE;
    BEGIN
    htree := Find_Item('block28.tree8');
    find_node := :SYSTEM.TRIGGER_NODE;
    ftree.set_tree_node_property(htree, find_node, ftree.NODE_ICON, 'D:\ico\Ico\favorite.ico');
    END;
    Ftree.SET_tree_NODE_PROPERTY(htree, :SYSTEM.TRIGGER_NODE, Ftree.NODE_ICON, 'print');And also when mouse double click
    declare
    al_button number;     
         pl_id ParamList;
         v_emp_id     number;
         e_child_rec  exception;
         pragma exception_init(e_child_rec, -02292);
         len number := 3; --variable which tells till what length from last not to copy from first string
    begin
         v_emp_id := ftree.get_tree_node_property(find_item('Block28.tree8'),
                                                               :system.trigger_node,
                                                                ftree.node_value);
    SET_BLOCK_PROPERTY('block3', DEFAULT_WHERE, 'acc_id = ''' || V_emp_id|| '''');
    go_block('block3');
    EXECUTE_QUERY;
    exception
           when e_child_rec then
                Message ('Go Kimi Go');
    end;
      Now when i double click the mouse its show tree icon
    I want when i run my module its show me all node icon
    Hope this time i clear my question
    Regards
    Shahzaib ismail

  • Please help with JTree Node Duplication

    Iam building a JTree which should not allow node duplication.
    1.)First i construct a ArrayList which stores all the previous nodes.
    treeNodeNames=new ArrayList();
    2.)i call the method
              readTreeNodeNames((DefaultMutableTreeNode)dtm.getRoot());
    3.)The method readTreeNodeNames is
    public void readTreeNodeNames(DefaultMutableTreeNode node) {
              if(node.toString().toLowerCase().length()!=0) {
              treeNodeNames.add(node.toString().toLowerCase());
              for(Enumeration en=node.children();en.hasMoreElements();) {
                   DefaultMutableTreeNode childNode=(DefaultMutableTreeNode)en.nextElement();      
                   if(childNode.toString().toLowerCase().length()!=0) {
                        treeNodeNames.add(childNode.toString().toLowerCase());
                   if(!childNode.isLeaf()) {
                        readTreeNodeNames(childNode);
    4.)i have four menu when right click a node add,modify,add subnode,delete.
    node duplication fails in my case.when should i call this method?should i call while doing every above mentioned operations or in TreeModelEvent implementations?
    i have mailed this problem already two times.but no one has not replied.Kinldy consider it and give me a solution.Or anyone having code for JTree Node duplication please send me to [email protected]

    Hi all,
    Any ideas to overcome this problem.?
    Thanks,
    Krish

Maybe you are looking for

  • Can you email Pages newsletter as HTML, not as attachment?

    I'm not a tech queen so be gentle! I want to do email newsletters but I want them to be HTML in the body of the email, not an attachment. is this possible in Pages?

  • AV adapter issues

    I cant mirror my iphone4 to my tv using an hdmi wire and a Av adapter, I can only ser videos and netflix bu t I thought I coukd display a lot more, am I doibg something wrong?

  • Regarding Hangcheck timer configuration in Oracle RAC 10g r2 installation

    Hi, Is it necessary to configure hangcheck timer in Oracle RAC 10g R2 installation . Can somebody guide when we should install the hangcheck timer in Linux oracle 10g R2. Best Regards Gupteswar Prasad Mishra Edited by: Gupteswar on Jan 25, 2010 8:42

  • Better to finish in 108050i or 108025p?

    HI! I'm working on a documentary shot mostly on a a 1080 50i HDV camera. Until recently, I was working in a 1080 50i HDV sequence (that is to say, I clicked yes when I inserted the first media into the timeline and FC asked me if sequence settings sh

  • Adobe Reader X funktioniert nicht einwandfrei

    Betriebssystem: Windows 7 Home Premium (64-bit Version) Version: Adobe Reader X (10.1.0) - Deutsch Hallo! Der Adobe Reader zeigt mir schon seit jetzt ungefähr 1-2 Wochen an "Update is ready to install". Wenn ich das dann aber bestätige, kommt die Mel