JTree - renderer

When i expand a jtree node, i am populating the content in runtime. I use model.insertNodeInto() method to insert the nodes. I have a dummy node in the first position so that i can get a +, so that i can expand the jtree node. I am changing the first dummy node to a node i want using model.valueForPathChanged() method. Everything works fine. I have a renderer attached. model.insertNodeInto() calls the getTreeCellRendererComponent() method successfully. But model.valueForPathChanged() is not calling the getTreeCellRendererComponent() by default.
My questions are:
1. Can i call the renderer forcefully for valueForPathChanged? If so, how?
2. Is there a easy way to get + for a node, even though the node has no child? i.e a leaf should have + , so that i can expand.
3. I tried deleting the first node, and insert a new node in first position. But removeNodeFromParent is calling model.reload() which is causing collapse of my node.

Best thing to do is implementing your own tree mobel
or tree node.
It has a method that should retun the number of
childs a node has. When it return a value greater
than zero you will get the + sign.I am implementing my own model. but can you help with the exact method to overload and return a value greater than 0. ?
Thanks.

Similar Messages

  • Setting a JTree renderer breaks the focus traversal order

    Hello,
    I am not sure what's wrong, but when I set a customize JTree renderer it breaks the focus traversal order of my UI. Can someone tell me what's wrong and also how to prevent it from changing the order of my components?
    For instance, if I have component order 1, 2, 3, 4, 5 to begin with and after I call JTree.setCellRenderer(new SomeRenderer()), the order would change to something like this 1, 2, 4, 5, 3
    To give you an overview of what I am creating, I am customizing a UI that will be plug into JFileChooser to replace the default UI. I know I can create my own FocusTraversalPolicy, but the thing is that I don't know some of my components ahead of time. As long as I can prevent the order change, I think it would be fixed.
    Regards,
    Soot

    Try creating a Short, Self-Contained, Compileable, Executable
    program which has this problem. Right now it would take a
    mind-reader to solve your problem.

  • JTree rendering bug

    A bug exists with JTree rendering where a huge treenode is rendered for no apparent reason. It happens infrequently, but I've noticed that it's happening more frequently since I started using jdk1.4.2.
    This seems to be the only place I can find mention of it : http://forum.java.sun.com/thread.jsp?forum=57&thread=217494
    One of the solutions mentioned was to setRowHeight() on the tree. I don't like it, but it seems to be the only way around the bug at present.
    Does anyone know of any potential problems which might arise from explicitly setting the row height on a JTree?

    I basically need to be able to edit the rendered JTable as normal.

  • JTree rendering extra node and leaf icons at the end of the label

    Hi,
    Does anyone know how to add an icon to a JTree node or leaf in such a way that it will be displayed behind the text label?
    In an example:
    - rootnode
    - childnode [icon]
    |- leaf
    + childnode [icon]
    Where -/+ are the default (un)collapse icons
    I'd like to apply this to show additional information by using icons with respect to a node.
    I couldn't find anything on the net besides changing the default open/close node icons, yet that's not what I'm aiming for here.

    use this one.I think it will help u.Gd lk
    tree =new JTree(root);
    DefaultTreeCellRenderer renderer =(DefaultTreeCellRenderer)tree.getCellRenderer();
    renderer.setLeafIcon(new ImageIcon(getClass().getResource("leafimages/3.gif")));
    renderer.setClosedIcon(new ImageIcon(getClass().getResource("leafimages/1.gif")));
    renderer.setOpenIcon(new ImageIcon(getClass().getResource("leafimages/2.gif")));
    renderer.setBackgroundNonSelectionColor(new Color(15,85,134));
    renderer.setBackgroundSelectionColor(Color.YELLOW);
    renderer.setTextNonSelectionColor(new Color(217,227,227));
    renderer.setTextSelectionColor(Color.RED);
    renderer.setHorizontalTextPosition(SwingConstants.LEADING);
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    tree.setFont(new Font("Tahoma",1,12));
    tree.setBackground(new Color(15,85,134));

  • JTree Renderer/Editor

    I have a custom renderer for my JTree that uses a JPanel with multiple fields within it. I am using the same JPanel for editing as well within a custom editor that extends the DefaultCellEditor. When I select to edit, it edits okay. When I focus away (click elsewhere), the cancelCellEditing() method gets called. The display then shows the original values (before editing). If I select the cell for editing again, it shows the previously "edited" values.
    It looks like the editor values are not getting transferred back to the renderer. Any ideas?
    Gil

    Does it work when you press ENTER before clicking out of the text field?

  • JTree rendering failure : big empy space displayed

    Hello,
    I have a problem using a JTree with jdk 1.5 update 10. I could not find anything in the bug database that seemed to link to this problem.
    I have created a JTree that displays the content of a directory under a root node (displayed). I have created my own renderer to customize the labels and i use a TreeModel to add and remove nodes.
    The problem (possibly a known bug): sometimes (it actually seems to be completely random), the Ttree "fails" rendering one of the label, resulting in a big white space instead of the usual label (icon + file name). Other labels in the tree are displayed correctly. The "big white label" can be selected and correctly links to the file it represents (information about the file is displayed correctly). All in all, everything works perfectly fine except one item is displayed as a big empty label.
    Is there any chance this could be a java bug ? If not is there any way i could know what causes this failure ?
    Regards.
    NB: some friend of mine that is working on a different project has exactly the same problem and can't find a solution either.

    I am having the identical problem and its driving me crazy. This started happening to me after I installed new hard drives and reinstalled the OS. I then transfered all the old settings from the old drive. Everything else seems to work perfectly. If you get anywhere with this let me know.
    Hy
    My goal: To import some pictures into iMovie. Maby
    add ken burns efects to them, add a bit of narration
    and some music, edit everything and export.
    The problem: Let say I use the following method: i
    click Media tab, then i click photos, then i select
    the photo, and in the Photo Settings click apply.
    iMovie then imports the photo, puts it in the
    timeline and then the dark red bar bellow apears (the
    one that would means rendering). The problem is,
    there is no light red getting over it (that would
    indicate rendering in progress). It's the same if i
    click and drag a photo into the clip browser (only
    the dark red is displayed on the bottom of the
    thumbnail). If i try to quit iMovie it warns me that
    rendering is in progress.
    It doesn't matter how big a photo is (i tried
    300x200px, 800x500px, 1500x1000px, 3000x2000px) or
    what format (jpg, tiff, png).
    I tried restarting the application and the sistem. I
    created another user to try if anything changes. I
    erased the preferences. I even tried copying the
    whole application from frend's computer (the same
    version and all). The dark red bar doesn't start to
    fill red (i checked in the terminal how much
    processor does it eat and it's on 7%, so it probablly
    means it's doing nothing)
    I have a 2Ghz, 2GB of ram Macbook 13" Intel core duo.
    I have 67 GB of space left (format: Mac-os extended -
    journaled), running OS-X 10.4.8 and updated to the
    latest updates. iMovie version is 6.0.3 (267.2).
    What else is there to do? Would reinstalling the
    whole sistem help and is there a way to keep all of
    my preferences and mail accounts and contacts, … in
    case i have to do that?
    thx in advance
    Peter
    Macbook 13"  
    Mac OS X (10.4.8)  

  • JTree renders only 10 records

    I have a data model based on toplink and datacotrols were created on the toplink session. When I introduced a jtree bound with a data collection within datacontrol, it rendered only top ten records from the collection. When it is rendered in a jtable, all records were rendered. Any one knows why?

    Figured it out. Needs to change the rangesize.

  • JTree Rendering

    Hello! Generally, JTree is rendered like :
    +x                                                     
    -+a
    ----a1
    ----a2
    ----a3
    -+b
    ----b1
    ----b2
    Is it possible to render a JTree like (think that '-' are empty characters):
    --------------------+x
    -------------a----------b
    ------- a1-a2-a3------b1-b2
    If it is possible, How I can render a JTree in that manner?

    use this one.I think it will help u.Gd lk
    tree =new JTree(root);
    DefaultTreeCellRenderer renderer =(DefaultTreeCellRenderer)tree.getCellRenderer();
    renderer.setLeafIcon(new ImageIcon(getClass().getResource("leafimages/3.gif")));
    renderer.setClosedIcon(new ImageIcon(getClass().getResource("leafimages/1.gif")));
    renderer.setOpenIcon(new ImageIcon(getClass().getResource("leafimages/2.gif")));
    renderer.setBackgroundNonSelectionColor(new Color(15,85,134));
    renderer.setBackgroundSelectionColor(Color.YELLOW);
    renderer.setTextNonSelectionColor(new Color(217,227,227));
    renderer.setTextSelectionColor(Color.RED);
    renderer.setHorizontalTextPosition(SwingConstants.LEADING);
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    tree.setFont(new Font("Tahoma",1,12));
    tree.setBackground(new Color(15,85,134));

  • JTree renderer problem

    I have listed below a shor example.
    What I need is a method to do each cell to be as wide as the tree is (see the red border line), even if I resize the window. And ofcourse, the tree should keep a minimum width so every cell is fully shown.
    I'll be waiting for your answers. Thanks.
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class TreeExample extends JFrame {
        public TreeExample() {
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            getContentPane().add(new JScrollPane(new SomeTree()));
            pack();
        public static void main(String[] args) {
           SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TreeExample().setVisible(true);
    class SomeTree extends JTree {
        public SomeTree() {
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
            String str = "***";
            for (int i = 0; i < 10; i++) {
                root.add(new DefaultMutableTreeNode(str));
                str += "***";
            setModel(new DefaultTreeModel(root));
            setCellRenderer(new SomeCellRenderer());       
            setBorder(BorderFactory.createLineBorder(Color.RED));
    class SomeCellRenderer extends JLabel implements TreeCellRenderer {
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                          boolean selected, boolean expanded,
                                                          boolean leaf, int row,
                                                          boolean hasFocus) {
            setOpaque(true);
            setText(value.toString());
            setBackground(Color.LIGHT_GRAY);
            return this;
    }

    The only problem i can figure is maybe the layout. Flowlayout is squeezing the size of the buttons so that they can appear in the little area that they do get. If you use borderlayout instead of the flowlayout, it may solve your problem. If that also doesn't work then set the minimum sizes of the labels.

  • JTree Renderer Question

    Hi,
    i want to change the icon of a particular leaf when the user double click it, but i dont want to change the rest of the other leafs icons i want them to keep the icon they have
    can this be posible??
    thank you

    create your own renderer.
    Search for "MyRenderer" on this page:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • Holly...JTree rendering problem

    okay guy, everything is done as what i post many many forum, then finally done except!!!
    except i still want my node (may be at the child or leaf level) to be able to response to my MouseEntered event (or may be other evet). another thing is that why isn't my JLabel or JTextPane get the hyperlink (i do implement the interface) show up instead of the entire hyperlink address in the JLabel (i try to clearify at the example code down there)?
    class TreeTextArea extends JEditorPane implements MouseListener, HyperlinkListener {
    other class method here
    // following is some part of the method, line is the hyperlink address
    lblSeqHyperlink.setText("<html><font face='times new roman'><u><a href='" + line + "'>testing...</a></u></font></html>");
    lblSeqHyperlink.setEditable(false);  // i've trying to true, the same
    lblSeqHyperlink.addHyperlinkListener(this);
    add(lblSeqHyperlink);
    // another method, but no response at all
    public void mouseEntered(MouseEvent e) {
            int curType = Cursor.HAND_CURSOR;
            lblSeqHyperlink.setCursor(new Cursor(curType));
            lblSeqHyperlink.setToolTipText("testing onli...");
    }any idea? thank a lot

    Code speaks for 1000 words... ;)
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.net.*;
    public class LinkTest extends JFrame
         public LinkTest()
              super("Link test");
              String line="http://www.gempukku.com/";
              JEditorPane editorPane=new JEditorPane();
              editorPane.setContentType("text/html");
              editorPane.setText("<html><font face='times new roman'><u><a href='" + line + "'>testing...</a></u></font></html>");
              editorPane.setEditable(false);
              editorPane.addHyperlinkListener(
                        new HyperlinkListener()
                              * Called when a hypertext link is updated.
                              * @param e the event responsible for the update
                             public void hyperlinkUpdate(HyperlinkEvent e)
                                  HyperlinkEvent.EventType et=e.getEventType();
                                  if (et==HyperlinkEvent.EventType.ENTERED)
                                       setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                                  else if (et==HyperlinkEvent.EventType.EXITED)
                                       setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                  else if (et==HyperlinkEvent.EventType.ACTIVATED)
                                       URL url=e.getURL();
                                       System.out.println("Link: "+url.toString()+" was clicked.");
              this.getContentPane().add(new JScrollPane(editorPane));
         public static void main(String[] args)
              LinkTest frm=new LinkTest();
              frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frm.setBounds(0, 0, 400, 300);
              frm.setVisible(true);
    }

  • JTree-Renderer Panels - any good link?

    Hello again
    I am really stuck please could anybody give me a good link where TreeCellRenderer are good explained. I've posted already a topic but it seems nobody can help.
    I want to put JPanels as nodes where each Jpanel displays a model of permissions with checkboxes.
    Thank you very much.

    Hello again
    I am really stuck please could anybody give me a good link where TreeCellRenderer are good explained. I've posted already a topic but it seems nobody can help.
    I want to put JPanels as nodes where each Jpanel displays a model of permissions with checkboxes.
    Thank you very much.

  • Rendering alternate colors in JTree

    I have a JTree within a scrollpane.
    What I would like to do is have every alternate line on the JTree rendered with one of 2 colors, i.e. line 1 is blue, line 2 is yellow, line 3 is blue etc.
    The tricky bit is that I want this color to fill the width of the scrollpane - changing the background of the JLabel color in the renderer will only update from the tree node to the right of the scrollpane (it leaves the area to the left of the node blank).
    Am I making any sense?

    Try this
    regards
    Stas
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    public class Test {
    JScrollPane scroll;
    JTree tree;
    public Test() throws Exception {
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode node1=new DefaultMutableTreeNode("node1");
    DefaultMutableTreeNode node2=new DefaultMutableTreeNode("node2");
    root.add(node1);
    root.add(node2);
    DefaultMutableTreeNode subnode2=new DefaultMutableTreeNode("node2_1");
    node2.add(subnode2);
    subnode2=new DefaultMutableTreeNode("node2_2");
    node2.add(subnode2);
    subnode2=new DefaultMutableTreeNode("node2_3");
    node2.add(subnode2);
    tree=new JTree(root);
    tree.setCellRenderer(new MyRenderer());
    frame.getContentPane().add(tree);
    frame.setBounds(100,100,200,200);
    frame.show();
    public static void main(String[] args) throws Exception {
    new Test();
    class MyRenderer extends DefaultTreeCellRenderer {
    public MyRenderer() {
    super();
    setOpaque(true);
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel,
    boolean expanded,
    boolean leaf, int row,
    boolean hasFocus) {
    JLabel l=(JLabel)super.getTreeCellRendererComponent(tree, value,
    sel,
    expanded,
    leaf, row,
    hasFocus);
    l.setPreferredSize(new Dimension(5000,20));
    if (row % 2==0) {
    l.setBackground(Color.CYAN);
    else {
    l.setBackground(Color.YELLOW);
    return l;

  • JTree calling setSelectionPath() does not highlight new selection

    I have looked throughout many forum entries and this question has been asked a few times but I have not seen a solution that works at least for me.
    When I do the following:
              TreePath path = new TreePath(...)
    this.tree.setExpandsSelectedPaths(true);          // not sure if I need this
              this.tree.getSelectionModel().setSelectionPath( path ); // this alone should work correct?
              this.tree.scrollPathToVisible(path);
    The original selection disappears (no highlighting) but the new one selected does not
    I have also tried calling just for fun ...
         this.tree.getSelectionModel().resetRowSelection();
    and this.tree.getSelectionModel().reload( path.getLastComponent() );
    Does anybody have an idea of what may be going wrong ? The selection path is valid as I have verified it with the debugger.
    Any ideas or suggestions are much appreciated
    thanks
    Doug

              TreePath path = new TreePath(...)
    The devil is in the details... Unfortunately your case's details are in the ellipsis! :o)
    Try to provide an SSCCE to get informed help, otherwise you can only hope that we guess well. That being said, here is my "guess":
    A preliminary: JTree renders selection by comparing nodes pathes with the selection path(es).
    As is common in the Java world, these comparisons rely on the equals() methods of the objets that make up the TreePath's components.
    If any of the classes involved does not override equals, the corresponding components objects will be considered equals only if they are identical. In other words, a TreePath which contain a "new" instance of whatever class that does not override equals() will never be considered equal to any TreePath created formerly.
    Now comes the gory part: DefaultMutableTreeNode (which is the most often common build block of TreeModels and TreePathes) does not override equals().
    So if your TreePath are made of DefaultMutableTreeNode components, they will never be considered equal unless they use the same DefaultMutableTreeNode instances, which would somewhat not be a common nor practical way of building TreePathes.
    The original selection disappears (no highlighting) but the new one selected does not Under my assumption:
    - the original selection disappears (because by construction the original selection's TreePath it is not equals() to the TreePath passed in argument to setSelectionPath(...)).
    - no new selection is rendered (because by construction no TreePath in the JTree's model can be equals() to the TreePath argument).
    Does anybody have an idea of what may be going wrong ? The selection path is valid as I have verified it with the debugger.Under my assumption:
    - you may have verified that the TreePath seemingly contained the expected values (often rendered in a debugger using toString() calls)
    - you may have overlooked that the TreePath components were not the same references.
    - you may not have executed step-by-step the TreePath.equals() methods nor the equals() method of the path's components.
    Keep in mind that this is just an assumption, based on your code fragment (and on prior painful experience with JTree). If i'm off base and you still need help, please post an SSCCE as sugested previously.
    Edited by: jduprez on Oct 11, 2009 12:53 PM

  • Cant we underline Jtree Node?...need help please

    Hi friends,
    sorry for repeating the question BUT i couldnt get any solution for this
    problem. My Jtree renderer extends DefaultTreeCellRenderer which ,in turn,
    extends JLabel.
    I want to make Underline possible for its Nodes.
    I am able to make it Bold,Italic ,change size and all BUT not underline.
    HOW to do that.
    Please give me some suggestion.
    thanx,
    Rajesh

    Hi Rajesh.
    I havn't tried these suggestions, but you can give them a try..?
    If your renderer for your node is a JLabel, you might be able to use html markup. So wrap the text for your label in...
    <html><u> // your text // </u></html>
    or.... you could try something with this code... (???)
    Font f=new Font("Times", Font.BOLD, 24);
    AttributedString ats=new AttributedString("Magic");
    ats.addAttribute(TextAttribute.FONT, f);
    ats.addAttribute(TextAttribute.UNDERLINE,
              TextAttribute.UNDERLINE_ON);which I found from :
    http://developer.java.sun.com/developer/onlineTraining/Media/2DText/exercises.html
    but you might find these useful too.
    http://developer.java.sun.com/developer/onlineTraining/Media/2DText/style.html
    http://developer.java.sun.com/developer/onlineTraining/Media/2DText/more.html
    ... hope this has helped.
    Ollie.

Maybe you are looking for

  • I need to put photos from my iPod to my computer

    My daughter's iPod touch has this very large block of "other" taking up more than 2gb of space of her device. I've exhausted all options and now we can't seem to get it to sync to wifi properly anymore. I want to do a complete reset on her iPod. Rest

  • Stop execution of a loop in an event structure

    I tried searching the forums to avoid posting a duplicate, but most I could not open most of the vi's as they were higher version. I put in a dummy while loop in an event structire i intend to use. Once I start executing the while loop, I am not able

  • How to retreive and display return value from BAPI

    Hello, I am using SUP to create a sales order application. In my MBO I have a create operation which calls a BAPI to create a sales order. How can I retrieve the return value (saled doc number) and display it on a screen and display it as an Alert of

  • How to set up a hotspot

    Hi, Using Network Manager, I can set up a hotspot while using wired connection. However, is it possible to set up a hotspot using a wireless connection? It seems OK for Windows. Thanks for advice.

  • Why can I not open PDF email attachments?

    Normally on my iPhone I'm able to simply click on the PDF attachment at the bottom of an email and it opens for me to read but I just got an iPad and it doesn't seem to do that. When I click attachments in my email nothing happens.  But for instance