JTree node lazy loading + icons problem

Hi all,
I need to build a large tree (10000 nodes). Since this is large to load all at once, i want to load the last level dynamically using the 'treeWillExpand'
Level 1
--Level 2
---Lever 3
----Node loaded dynamically 4.1
----Node loaded dynamically 4.2
----Node loaded dynamically 4.3
What i do is, i load all nodes in level 1,2,3 when application is initially loaded. In the Level 3 node, I add 1 dummy child node. I call it 'Waiting ...'. This I do because I want to display the 'handle' next to Level 3 node. Later on, when i click on the Level 3 'handle', I use this 'treeWillExpand' code:
private void TreeWillExpand(javax.swing.event.TreeExpansionEvent evt) throws javax.swing.tree.ExpandVetoException {
        path = evt.getPath();
        //3 - Level 3
        if (path.getPathCount() == 3) {
            //here I get rid of the 'Waiting ...' node
            computerNode.removeAllChildren();
            //here I add all level 4 nodes
            Iterator it = ArrayList.iterator();
            while (it.hasNext()) {
               .. here i load all Level 4 nodes
Questions:
1.
Is the approach above a good approach, how to load children 'lazilly'?
2.
I also use custom renderer to display different icons for every "tree" level. When I initially expand the 4th level, everything works fine !!! Then I collapse the 4th level and expand it again and here my problem starts:
- my 4th level icon is set to 'root level icon' instead of '4th level' icon. This does not happen, if computerNode.removeAllChildren(); method is removed from listening above
My custom renderer:
class MyTreeRenderer extends DefaultTreeCellRenderer {
    Icon rootIcon;
    Icon siteIcon;
    Icon computerIcon;
    Icon computerUnscannedIcon;
    Icon softwareIcon;
    public MyTreeRenderer(Icon rootIc, Icon siteIc, Icon computerIc, Icon computerUnscannedIc, Icon softwareIc) {
        rootIcon = rootIc;
        siteIcon = siteIc;
        computerIcon = computerIc;
        softwareIcon = softwareIc;
        computerUnscannedIcon = computerUnscannedIc;
    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);
        //we can draw 4 icon types here
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
        String nodeType = (String) node.getUserObject();
        int level = node.getLevel();
        if (level == 0) {
            setIcon(rootIcon);
        } else if (level == 1) {
            setIcon(siteIcon);
        } else if (level == 2) {
            //make difference between scanned and unscanned computer
            if (node.getDepth() > 0) {
                setIcon(computerIcon);
            } else {
                setIcon(computerUnscannedIcon);
        } else if (level == 3) {
            setIcon(softwareIcon);
        return this;
}Any idea, what am i doing wrong?

durino13 wrote:
1. Is the approach above a good approach, how to load children 'lazilly'?Sounds pretty reasonable to me.
2. I also use custom renderer to display different icons for every "tree" level. When I initially expand the 4th level, everything works fine !!! Then I collapse the 4th level and expand it again and here my problem starts: my 4th level icon is set to 'root level icon' instead of '4th level' icon. This does not happen, if computerNode.removeAllChildren(); method is removed from listening above
Any idea, what am i doing wrong?Ummmm... Load the model the first time (only) the node is expanded... Putz!
And I suggest you listen deeply to Mr Jacobs... He really does know what he's talking about ;-)
... and not this time, but in future: Swing questions are best asked in [THE Swing Forum|http://forums.sun.com/forum.jspa?forumID=57].
Cheers. Keith.

Similar Messages

  • The loading icon keeps turning after the site has loaded, and since the last update, have had quite a few problems loading some sites, specifically secure sites such as bank websites and "My Ebay" when I try to sign in.

    Don't have any more details....the loading icon problem happens on quite a few websites, and I am having trouble signing into secure websites, like my bank website...

    Don't have any more details....the loading icon problem happens on quite a few websites, and I am having trouble signing into secure websites, like my bank website...

  • Problem with module lazy loading in flex 3

    Hi every body!
    I have some problems with Module lazy loading. I am using flex 3.5, Module-flex3-0.14, parsley 3.2.
    I can't get the LazyModuleLoadPolicy working correctly.
    In my main application (the one that loads the modules), my parsley context is the following:
            <cairngorm:LazyModuleLoadPolicy objectId="lazyLoadPolicy" type="{ OpenViewMessage }" />
         <cairngorm:ModuleMessageInterceptor type="{ OpenViewMessage }"/>
         <cairngorm:ParsleyModuleDescriptor objectId="test"
              url="TestModule.swf"
              applicationDomain="{ClassInfo.currentDomain}"
         />
    And to load my module:
    [Inject(id="test")]
    [Bindable] public var test:IModuleManager;
    <core:LazyModulePod
         id="moduleLoader"
         moduleManager="{test}"
         moduleId="testModule"
    />
    with  LazyModulePod.mxml:
    <mx:Canvas
        xmlns:mx="http://www.adobe.com/2006/mxml"
        xmlns:module="com.adobe.cairngorm.module.*"
        xmlns:parsley="http://www.spicefactory.org/parsley">
        <mx:Script>
            <![CDATA[
                import com.adobe.cairngorm.module.ILoadPolicy;
                import com.adobe.cairngorm.module.IModuleManager;
                [Bindable]
                public var moduleId:String;
                [Bindable]
                public var moduleManager:IModuleManager;
                [Bindable]
                [Inject(id="lazyLoadPolicy")]
                public var lazyLoadPolicy:ILoadPolicy;
            ]]>
        </mx:Script>
        <parsley:Configure/>
        <module:ViewLoader id="moduleLoader"
            moduleId="{ moduleId }"
            moduleManager="{ moduleManager }"
            loadPolicy="{lazyLoadPolicy}">
             <!--<module:loadPolicy>
                  <module:BasicLoadPolicy/>
             </module:loadPolicy>-->
        </module:ViewLoader>
    </mx:Canvas>
    OpenViewMessage.as in a swc:
    public class OpenViewMessage
            private var _moduleId:String;
            private var _viewId:String;
            public function OpenViewMessage(moduleId:String, viewId:String)
                this._moduleId = moduleId;
                this._viewId = viewId;
            public function get viewId():String{
                return _viewId;
            [ModuleId]
            public function get moduleId():String
                return _moduleId;
    In another flex project, my module context is:
    <mx:Object
         xmlns:mx="http://www.adobe.com/2006/mxml"
         xmlns:controler="com.cegedim.myit.controler.*">
         <controler:WindowControler/>
    </mx:Object>
    The module implements IParsleyModule
    <mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
         implements="com.adobe.cairngorm.module.IParsleyModule"
         xmlns:spicefactory="http://www.spicefactory.org/parsley">
         <mx:Script>
              <![CDATA[
                   import org.spicefactory.parsley.flex.FlexContextBuilder;
                   import com.adobe.cairngorm.module.IParsleyModule;
                   public function get contextBuilder():ContextBuilderTag
                    return contextBuilderTag;
              ]]>
         </mx:Script>
         <spicefactory:ContextBuilder  id="contextBuilderTag" config="{ MyITTestModuleContext }"/>
         <spicefactory:Configure/>
    </mx:Module>
    and the WindowControler:
    public class WindowControler
         public function WindowControler(){}
         [Init]
            public function initialize():void
                Alert.show("Module Initialized");
            [MessageHandler(scope="local")]
            public function openViewMessageHandler(message:OpenViewMessage):void
                Alert.show("Opening view " + message.viewId + " in the module " + message.moduleId);
    If i uncomment the basicLoadPolicy in LazyModulePod.mxml and remove the lazyModuleLoadPolicy, everything works fine. The module is loaded when it's added to stage and it receives correctly messages dispatched to it. But with the lazy policy the module never loads.
    I may have missed something or there is somthing i don't understand because i tried the ModuleTest provided in example in cairngorm sources. It works fine (i mean loading the moduleA2 when receiving a message), but if i replace the change the lazyModulePolicy to listen to broadcasted messages instead of a pingMessage, the module never loads too.
        <cairngorm:LazyModuleLoadPolicy objectId="lazyLoadPolicy" type="{ BroadcastMessage }" />
        <cairngorm:ModuleMessageInterceptor
            type="{ BroadcastMessage }" moduleRef="moduleA" />
    public class BroadcastMessage
        public function BroadcastMessage()
    If someone has any clue, i'll be happy to test it =)
    Thanks.

    Hello, back on my issue, i tested a little bit more the message dispaching.
    I read the lazyLoadPolicy class and noticed that it always has to have a ModuleId property in the message to work, that's why the broadcast message didn't work to awake the module with the lazy loading policy.
    So i added copy of my module:
         <cairngorm:ParsleyModuleDescriptor objectId="test"
              url="TestModule.swf"
              applicationDomain="{ClassInfo.currentDomain}"
         />
         <cairngorm:ParsleyModuleDescriptor objectId="testbis"
              url="TestModuleBis.swf"
              applicationDomain="{ClassInfo.currentDomain}"
         />     
    Set them both with a basicLoadPolicy, and tries to dispatch a message to only one of them using the ModuleId metatag. I then noticed that both modules received the message and not only the one i expected.
    I then changed the ModuleMessageInterceptor configuration to dispatch to only one kind of module:
    <cairngorm:ModuleMessageInterceptor type="{ OpenViewMessage }" moduleRef="test"/>
    and this worked as expected. Only the first module catched the message. I am obiously messing with the ModuleId metatag but i cannot see what's wrong...
    I compiled with
    -keep-as3-metadata+=ModuleId
    but this hasn't changed anything...

  • JTree - node text doesn't fit when shown with icon

    When I start off my JTree with a long string text for the node (without any icon...used setLeafIcon( null )... it displays fine. But during the execution of hte program an icon may appear next to a particular node - but when this happens, the icon displays fine and the text of the node is cut off (you just see a couple letters followed by the usual "...").
    Any ideas?

    Thanks for the reply. I am not sure how to use that for what I'm doing...basically I am writing an AIM clone. And when a user sets an away message, I want an icon to appear next to their name, otherwise the icon is set to null. Here is the code I have right now for my tree cell renderer class (the tree class is a basic tree):
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.tree.*;
    import javax.swing.text.*;
    import java.util.*;
    import java.io.*;
    class MyTreeCellRenderer extends DefaultTreeCellRenderer {
         * Handle to the ClientTree.
        ClientTree clientTreeObj;
         * Constructor.
        public MyTreeCellRenderer( ClientTree ct ) {
            clientTreeObj = ct;
         * Gets the cell renderer for the current object
         * in the tree.
        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 we are at the root, take away the icons and set
        // the appropriate font.
        if (!leaf) {
            setClosedIcon( null );
            setOpenIcon( null );
            setToolTipText( null );
            setFont( new Font( "SansSerif", Font.BOLD, 14 ) );
        // we are at a leaf, so set the tooltip to be the username and
        // set the appropriate font.
        else {
            // make sure we are not at the "Users" node
            if ( !value.toString().equals( "Users" ) ) {
                // if the client has an away message, set the icon to a note icon
                if ( clientTreeObj.getJCC().getClientAwayMessage( value.toString() ).length() > 0 ) {
                    System.out.println( value.toString() + ": has a message..." );
                    setLeafIcon( new ImageIcon( "C:/JavaChat/JavaClient/images/message.jpg" ) );
                    ((DefaultTreeModel)tree.getModel()).nodeChanged((DefaultMutableTreeNode)tree.getPathForRow(row).getLastPathComponent() );
                    //tree.fireTreeExpanded( tree.getPathForRow( row ) );
                else {
                    setLeafIcon( null );
                    //tree.fireTreeExpanded( tree.getPathForRow( row ) );
                // get the connection time for the selected user
                // I TOOK OUT THE CODE TO CALCULATE THE TIME BECAUSE IT IS UNIMPORTANT AND LONG :)
                // set the tooltiptext to include the username and the online time
                String tooltip = " " + value.toString() + '\n' + "   Online time:" + '\t';
                    // days
                    if ( days > 0 ) {
                        if ( days == 1 )
                            tooltip += days + " day, ";
                        else
                            tooltip += days + " days, ";
                    // hours
                    if ( hours > 0 ) {
                        if ( hours == 1 )
                            tooltip += hours + " hour, ";
                        else
                            tooltip += hours + " hours, ";
                    // minutes (we always print at least 1)
                    if ( minutes > 1 )
                        tooltip += minutes + " minutes ";
                    else
                        tooltip += minutes + " minute ";
                    setToolTipText( tooltip );
                    setFont( new Font( "SansSerif", Font.PLAIN, 14 ) );
            return this;
        } // end getTreeCellRendererComponent
    } // end class MyRenderer

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

  • Facing problem with lazy loading in ejb3.0

    The following error is coming up when i try to access the collection in the entity entity bean. i am using entitymanager.find() to retrieve the entity. intial set of values are coming fine but when try to access the collection in the entity the error is coming up. one solution is to make the fetch type=eager. but can we do lazy loading with out any problem. the following is the error. kindly help me in this. do i need to do anything extra that mean have to add any annotations or anything.
    org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.lucid.erp.entities.EmployeeDTO.addresses, no session or session was closed
         at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
         at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
         at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
         at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
         at org.hibernate.collection.PersistentBag.get(PersistentBag.java:422)
         at com.lucidlabs.erp.actions.EmployeeAction.view(EmployeeAction.java:20)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
         at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
         at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
         at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
         at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
         at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:123)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:184)
         at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:105)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:207)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:74)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
         at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
         at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
         at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
         at

    this is transactions 101 material. Do you know about transactions and how they work? Do you know about managed entities?
    The problem you are having is that the addresses are accessed outside of the transaction in which the entity was fetched. That means there is no more database session and thus the lazy fetch cannot work. If you really need the addresses, you can at least force fetch them by calling getAddresses().size() right after you fetch the entity from the database; assuming that the transaction is still active at that point.

  • How to change icons of a JTree node dynamically

    Hi all!
    I want to change icon associated with a node dynamically ( i.e. after the tree has being displayed). How can i achieve this?
    Can any one provide me a sample code snippet.
    Thanks in advance
    Murali

    I have created CustomCellRenderer and i'm calling this class as follows
    tree.setCellRenderer((TreeCellRenderer) new CustomCellRenderer(true));
    The boolean value for the constructor (in this case it's true) will be set to
    a local variable in the CustomCellRenderer class. Then upon clicking a node in the tree the boolean value (true) is set and the icon for that node should be changed as specified in the CustomCellRenderer class.
    When i click on a node all the icons of that tree are disappearing.
    Can any one help me in this issue
    public class CustomCellRenderer
              extends          JLabel
              implements     TreeCellRenderer
    private ImageIcon          grayfolderImage;
    private ImageIcon          greenfolderImage;
    private ImageIcon          bluefolderImage;
    private ImageIcon          redfolderImage;
    private ImageIcon          whitefolderImage;
    private boolean               bSelected;
    boolean logfileDeleted;
         public CustomCellRenderer()
              grayfolderImage = new ImageIcon("C:\\images\\grayFolder.gif");     
              greenfolderImage = new ImageIcon("C:\\images\\greenFolder.gif");     
              bluefolderImage = new ImageIcon("C:\\images\\blueFolder.gif");     
              redfolderImage = new ImageIcon("C:\\images\\redFolder.gif");
              whitefolderImage = new ImageIcon("C:\\images\\whiteFolder.gif");     
         public CustomCellRenderer(boolean logfileDeleted){
              this.logfileDeleted = logfileDeleted;
         public Component getTreeCellRendererComponent( JTree tree,
                             Object value, boolean bSelected, boolean bExpanded,
                                       boolean bLeaf, int iRow, boolean bHasFocus )
              // Find out which node we are rendering and get its text
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              String     labelText = (String)node.getUserObject();
              this.bSelected = bSelected;
              // Set the correct foreground color
              /*if( !bSelected )
                   setForeground( Color.black );
              else
                   setForeground( Color.red ); */
              // Determine the correct icon to display
              if( labelText.equals( "ioexception001" ) )
                   setIcon( redfolderImage );
              else if( labelText.equals( "ioexception002" ) )
                   setIcon( greenfolderImage );
              else if( logfileDeleted ==true )
                   setIcon( whitefolderImage );
              else if( labelText.equals( "ioexception004" ) )
                   setIcon( redfolderImage );
              else
                   setIcon(bluefolderImage);
              // Add the text to the cell
              setText( labelText );
              return this;
         // This is a hack to paint the background. Normally a JLabel can
         // paint its own background, but due to an apparent bug or
         // limitation in the TreeCellRenderer, the paint method is
         // required to handle this.
         public void paint( Graphics g )
              Color          bColor;
              Icon          currentI = getIcon();
              // Set the correct background color
              bColor = bSelected ? SystemColor.textHighlight : Color.white;
              g.setColor( bColor );
              // Draw a rectangle in the background of the cell
              g.fillRect( 0, 0, getWidth() - 1, getHeight() - 1 );
              super.paint( g );
    }

  • Ho to set different Icon for different Jtree Nodes dynamically??

    Dar Friends:
    I have following code.
    But if poosible I hope to:
    [1]. Dynamically assign or st each node with different Icons;
    [2]. these icons have different sizes, hope to resize them with same size, ie. 20X 20
    But try whole day, no idea how to to it,
    Can somebody throw a light??
    Thanks
    Good weekends
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    /** JTree with missing or custom icons at the tree nodes.
    *  1999 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    public class CustomIcons extends JFrame {
      public static void main(String[] args) {
        new CustomIcons();
      private Icon customOpenIcon = new ImageIcon("images/Circle_1.gif");
      private Icon customClosedIcon = new ImageIcon("images/Circle_2.gif");
      private Icon customLeafIcon = new ImageIcon("images/Circle_3.gif");
      public CustomIcons() {
        super("JTree Selections");
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode child;
        DefaultMutableTreeNode grandChild;
        for(int childIndex=1; childIndex<4; childIndex++) {
          child = new DefaultMutableTreeNode("Child " + childIndex);
          root.add(child);
          for(int grandChildIndex=1; grandChildIndex<4; grandChildIndex++) {
            grandChild =
              new DefaultMutableTreeNode("Grandchild " + childIndex +
                                         "." + grandChildIndex);
            child.add(grandChild);
        JTree tree3 = new JTree(root);
        tree3.expandRow(3); // Expand children to illustrate leaf icons
        DefaultTreeCellRenderer renderer3 = new DefaultTreeCellRenderer();
        renderer3.setOpenIcon(customOpenIcon);
        renderer3.setClosedIcon(customClosedIcon);
        renderer3.setLeafIcon(customLeafIcon);
        tree3.setCellRenderer(renderer3);
        JScrollPane pane3 = new JScrollPane(tree3);
        pane3.setBorder(BorderFactory.createTitledBorder("Custom Icons"));
        content.add(pane3);
        pack();
        setVisible(true);
    }

    Thanks for your advice,I post my code as below, (I cannot post Max 5000, so post twice)
    [1]. main:
    import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    import java.awt.*;
         public class JTreeNew  extends JFrame {
           public JTreeNew() {
             super("Editable Tree Frame");
                JTreeSub js = new JTreeSub();
             setSize(200, 200);
            // WindowUtilities.setNativeLookAndFeel();
            // addWindowListener(new ExitListener());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
           public class JTreeSub  extends JTree implements TreeSelectionListener{
                DefaultTreeModel treeModel;
                JTree tree;
                ContainerIconNode selectedNode;
                public JTreeSub() {
                super();
                init();
                public void init(){
                  ContainerIconNode Root = new ContainerIconNode("images/Root.GIF");
                  ContainerIconNode Animal = new ContainerIconNode("images/Animal.GIF");
                  ContainerIconNode Cat = new ContainerIconNode("images/Cat.GIF");
                  ContainerIconNode Fish = new ContainerIconNode("images/Fish.GIF");
                  ContainerIconNode GoldFish = new ContainerIconNode("images/GoldFish.GIF");
                  ContainerIconNode CatFish = new ContainerIconNode("images/CatFish.jpg");
                  ContainerIconNode Solomon = new ContainerIconNode("images/Solomon.GIF");
                  ContainerIconNode DogFish = new ContainerIconNode("images/DogFish.GIF");
                  ContainerIconNode Dog = new ContainerIconNode("images/Dog.jpg");
                  ContainerIconNode Mouse = new ContainerIconNode("images/Mouse.GIF");
                  ContainerIconNode Chicken = new ContainerIconNode("images/Chicken.GIF");
                  ContainerIconNode Pig = new ContainerIconNode("images/Pig.GIF");
                  treeModel = new DefaultTreeModel(Animal);
                  tree = new JTree(treeModel);
                  tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                  ToolTipManager.sharedInstance().registerComponent(tree);
                  //Listen for when the selection changes.
                 tree.addTreeSelectionListener(this);
                  tree.setEditable(true);
                  treeModel.insertNodeInto(Animal,Root, 0);
                  Animal.add(Cat);
                  Animal.add(Fish);
                  Fish.add(GoldFish);
                  Fish.add(CatFish);
                  Fish.add(Solomon);
                  Fish.add(DogFish);
                  Animal.add(Dog);
                  Animal.add(Mouse);
                  Animal.add(Chicken);
                  Animal.add(Pig);
                  tree.expandRow(3); // Expand children to illustrate leaf icons
         //         DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
         //         renderer.setOpenIcon(Animal.getImageIcon());
         //         renderer.setClosedIcon(Dog.getImageIcon());
         //         renderer.setLeafIcon(CatFish.getImageIcon());
         //         tree.setCellRenderer(renderer);
                  ImageIcon startIcon = new ImageIcon("images/89.gif");
                  tree.setCellRenderer(new MyRenderer(startIcon));
                  getContentPane().add(tree, BorderLayout.CENTER);
              @Override
              public void valueChanged(TreeSelectionEvent e) {
                   selectedNode = (ContainerIconNode)
                                    tree.getLastSelectedPathComponent();
                 if (selectedNode == null) return;
                 Object nodeInfo = selectedNode.getUserObject();
                 if (selectedNode.isLeaf()) {
                      System.out.println("<JTreeNew> Node is  leaf=");
                 } else {
                      System.out.println("<JTreeNew> Node is  folder");
           private class MyRenderer extends DefaultTreeCellRenderer {
                 Icon nodeIcon;
                 public MyRenderer(ImageIcon icon) {
                      nodeIcon=icon;
                 public Component getTreeCellRendererComponent(
                                     JTree tree,
                                     Object value,
                                     boolean sel,
                                     boolean expanded,
                                     boolean leaf,
                                     int row,
                                     boolean hasFocus) {
    //                  System.out.println("<JTreeNew> Tree="+ tree);
    //                  System.out.println("<JTreeNew> nodeIcon="+ nodeIcon);
                      System.out.println("\n<JTreeNew> value="+ value);
                      System.out.println("<JTreeNew> sel="+ sel+"\n");
    //                  System.out.println("<JTreeNew> expanded="+ expanded);
    //                  System.out.println("<JTreeNew> leaf="+ leaf);
    //                  System.out.println("<JTreeNew> row="+ row);
    //                  System.out.println("<JTreeNew> hasFocus="+ hasFocus);
                     return this;
           public static void main(String args[]) {
                JTreeNew st = new JTreeNew();
                st.setVisible(true);
         }

  • 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

  • Is anyone having problems syncing iPhoto to iPad 2 after iOS 7.0.3 update? when I click on photos tab, I get a circular dashed loading icon that is perpetually there. It never loads the library

    When I click on photos tab, I get a circular dashed loading icon that is perpetually there. It never loads the library. i dont even see the iphoto content! thx for your help!

    I am certain too that it is possibly the 7.0.3 update. Have you tried restoring from backup? I am uncertain that might work but its worth a try.
    If that doesn't work I suggest that you give feedback to Apple directly. The more about this problem, the quicker it will get resolved.
    Here's the link: http://www.apple.com/feedback/ipodtouch.html
    Best,
    OrlaG

  • I just got an eMac G4-1Ghz/256/80/SuperDrive/56k/220v the problem is, it's stuck on theLoading Screen everytime i turn it on it wont go any further it's stuck on the Gray Apple logo with whiteBG and the loading icon that keeps circling any ideas?

    i got this emac from my uncles friend, and they said it's still working so i was likeok lemme see. and when i turned it on i was like "nice it really is working" but right after it went to the loading screen (Gray apple logo with a whiteBG and the loading icon that keeps circling) it wont go any further.. it just stays like that forever.. OMG any ideas???? thanks

    Hello, do you have the Install Discs for it?
    "Try Disk Utility
    1. Insert the Mac OS X Install disc, then restart the computer while holding the C key.
    2. When your computer finishes starting up from the disc, choose Disk Utility from the Installer menu at top of the screen. (In Mac OS X 10.4 or later, you must select your language first.)
    *Important: Do not click Continue in the first screen of the Installer. If you do, you must restart from the disc again to access Disk Utility.*
    3. Click the First Aid tab.
    4. Select your Mac OS X volume.
    5. Click Repair Disk, (not Repair Permissions). Disk Utility checks and repairs the disk."
    http://docs.info.apple.com/article.html?artnum=106214
    Then try a Safe Boot, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, reboot when it completes.
    (Safe boot may stay on the gray radian for a long time, let it go, it's trying to repair the Hard Drive.)
    If perchance you can't find your install Disc, at least try it from the Safe Boot part onward.

  • 8.1.2 6plus  Facebook stuck on loading icon and blank page

    As the title states, once in a week when I open Facebook all that appears is the loading icon and it stays that way. I can't tap the bottom options either (messages, notifications etc.). If I kill the app/restart the phone and re-open facebook, the same loading icon appears. I have to delete and re-install app in order to use normally again. Anyone else experience this? TIA

    That happens occasionally with the Facebook App. It's probably due to a problem on (or communicating to) the Facebook servers or just a bug in the App. There's not much that you can do about it until Facebook fixes their problems.

  • It doesn�t work lazy loading with remote client (toplink)

    I am trying to use lazy loading in a @ManyToOne field but I get an exception. I have been reading in some oracle tutorials that it's necesary use -javaagent:.../lib/toplink-essentials-agent.jar for that it works because this argument activate dynamic weaving in JavaSE. I have put this command line argument javaagent but it doesn't work. Why? Can I have to do another thing? I have done a lot of tests in base to comments read in another forums but I only obtains an exception.
    Caused by: java.io.IOException: Mismatched serialization UIDs
    NOTE: The server use toplink and the remote client query the entitties through a session bean of the server. Besides, I am using Glassfish (Sun application server and toplink).
    Thanks in advance.
    hayken

    At first, thank you for your reply.
    I know that I haven´t explained the problem too well. I have a stateless bean with one remote method that execute a query an returns an entity like this
    @Entity
    public class ModuloEntity extends Serializable
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idModulo;
    private String nombre;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="IdProyecto")
    private ProyectoEntity proyecto;
    The remote client invoke this method and in that moment I get this exception.
    21-may-2007 18:55:48 com.sun.corba.ee.impl.encoding.CDRInputStream_1_0 read_value
    ADVERTENCIA: "IOP00810211: (MARSHAL) Exception from readValue on ValueHandler in CDRInputStream"
    org.omg.CORBA.MARSHAL: vmcid: SUN minor code: 211 completed: Maybe
    at com.sun.corba.ee.impl.logging.ORBUtilSystemException.valuehandlerReadException(ORBUtilSystemException.java:7053)
    Caused by: java.io.IOException: Mismatched serialization UIDs : Source (Rep. IDRMI:com.syskonic.gesplan.entities.ModuloEntity:6D06A8C14D488FFF:8E6FC8687EA9E512) = 8E6FC8687EA9E512 whereas Target (Rep. ID RMI:com.syskonic.gesplan.entities.ModuloEntity:1C6925798CDFD3DF:3455DBF4457AE337) = 3455DBF4457AE337
    at com.sun.corba.ee.impl.util.RepositoryId.useFullValueDescription(RepositoryId.java:573)
    If I look the server log, I can see that the call has not been produced, it doesn´t show any exception. It looks that the object managed by the server and the remote client aren´t the same and the corba service doesn´t work when remote client call session method. If I change the ModuloEntity and remove the fetch attribute then all this process executes correctly. The problem is in this attribute.
    NOTE: I am using the javaagent command line argument.
    Hayken

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

  • Jtree node info

    Hi there all,
    I am making a swing application using jtree and i have a problem faced.
    I need some help.
    I create a default node
    final Object bookId=me.getKey();
    inal Object bookName=me.getValue();
    DefaultMutableTreeNode book = new DefaultMutableTreeNode(here??);
    i have a treemap and in this there is an id and a name list.
    what i want to do,
    when i click to a node in a tree i want to get both name and id for this node. but i couldnt.
    How can i put bot name and id in the nodes? Names will be nodes name?
    thanks.

    public class Book {
      Object id;
      Object name;
    new DefaultMutableTreeNode(book);Then write a TreeCellRenderer to display the node-with-book how you want it (or override toString() for the easy way out).

Maybe you are looking for

  • Best technique for "stripping" an XML file

    I've been coding Java for a while now, but this is my first foray into Java-based XML processing. Here's the problem: I want to take an XML file, extract from it a simpler data set, and output that as a new XML file. (Parse, extract, serialize.) Ther

  • Replaced Hard Drive Not Recognized/Boot--Bizarre!

    Help. I swapped a failing 30gb drive out of my 12" G4 1.33GHz Powerbook and replaced it with an 80gb WesternDigital. The Powerbook refuses to recognize it. I've been around and around the boards looking for answers: * Everytime I start I get a blinki

  • Application Realm Issue

    WLS 8.1 SP5 I nominate a realm in application.xml. This realm is not the default realm. The reason is that I want the WLS authenticiation base (admin etc) away from the app realm. Consequently, the realm is not recognised when the app is deployed. Wh

  • Continuous background job

    Hi Experts, I  have a requirement , where a program need to be executed as a continuous job. In the logic of the program, there is a 'Do.. EndDo'  , which would be continuously running. I have set the program as a background job, where I have a singl

  • How to Create Multiple Partitions in Windows?

    I have just carried out a clean install of Lion then used Boot Camp to install Windows. With Snow Leopard I had the ability to create multiple partitions in Windows but this seems impossible in Lion for whatever reason. Can anyone please tell me how