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

Similar Messages

  • How to set different icons for different windows which is seen in the top left corner?

    Hi
    How to set different icons for different windows which is seen in the top left corner? I know when building exe there is a option to edit icons or add icons and that icon is default for all the windows in the project. But i want different icons for different windows which is possible in VB.
    Is there any way to set icon by calling any dlls.
    Thanks & Regards
    Samuel J
    [email protected]

    Hi Sam,
    no problem. See the attachment.
    Mike
    Attachments:
    TestIcon_LV85.zip ‏44 KB

  • How to display different icon, for different node of jtree

    Hi All,
    How to display different icon, for different node of jtree

    you haven't responded to my last post here: [http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676|http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676]

  • I want to change different icon for different leaf node

    Hi,
    i am reading file system(win 2000)and showing in a tree.i want to
    show different icon for different file extension.
    Pl suggest me with sample code,how should i do?
    Thanx

    Hi...
    To do this, u need to write ur own TreeCellRenderer.
    ex :
    class FileSystemTreeCellRenderer extends JLabel implements TreeCellRenderer
         File file= null;
         public FileSystemTreeCellRenderer(File f)
              this.file = f;
         public Component getTreeCellRendererComponent
                   JTree tree,
                   Object value,
                   boolean selected,
                   boolean expanded,
                   boolean leaf,
                   int row,
                   boolean hasFocus
              if(file.isDirectory())
                   setIcon("your image");
                   setText("file/dir name");
              else
                   setIcon("your other image");
                   setText("file/dir name");
         return this;
    Hope it suits ur need .. (also, using the file extensions, u can set different icons following the above strategy...)
    Regards,
    Ramanujam

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

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

  • How to set different icon for different type of document

    Hi,
    In my repository, we have different kinds of document (crystal report, word document, excel, jpg ...) and we wanna show specific icon for each kind. In my used ResourceRender I cann't see where to change (rnd:icon?)
    Could someone tell me how to achieve that? Thanks
    Ray

    Hi Ray Li,
    in KM icons are mapped to mime types. You can add a mapping or change an existing one as follows:
    1. Go to Systemadministrarion - System Configuration - Knowledge Management - Content Management - Utilities - Icons
    2. Add your mime mapping or change an existing one. To determine the correct mime type of your documents, just have a look at the details dialog in KM.
    3. The path to the icons points (by default) to following directory on your KM server: usr\sap\SID\SYS\global\config\cm\etc\public\mimes\images
    Here you can replace images or add some new.
    Hope this helps,
    Carsten
    Seems like somebody thought the same thought bit faster than I did. Would like to delete my answer that does not contain any additional info. But dunno how to.
    Message was edited by: Carsten Buechert

  • Different Icon in a JTree

    Helle mates,
    is it possible to display different icons in a JTree?
    At present, I have the same folder-icons for all folders and the same leaf-icons for each leaf but I want different pics for each folder and for each folder different leaf-icons.
    Is that possible?
    I searched for it but nothing could help me so far. Hopefully, someone got an idea in here.
    Thank you so much

    you need a TreeCellRenderer. it will allow you to draw different icons for different nodes. for example like so:
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Model model = (Model)((DefaultMutableTreeNode)value).getUserObject();
        setBackgroundNonSelectionColor(model.conditionColor());
        setBackgroundSelectionColor(model.conditionColor().darker());
        setOpenIcon(model.icon());
        setLeafIcon(model.icon());
        setClosedIcon(model.icon());
        Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        if (selected) setForeground(Color.white);
        return c;
    aJTree.setCellRenderer(new MyTreeCellRenderer());
    :thomas

  • How to set different Icons for Jtreenode

    How to set different Icons for Jtreenode,i want to set icons for jtreenode,not only for leaf,open,closeicon,i hope that each node has a different icon.Thanks!

    you need to check for the node value within a renderer, then assign an icon based on what you expect to get back.
    check out this page. http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • Defining different icons for TreeNode by extending DefaultTreeCellRenderer

    Hello all,
    I'm using a JTree to display project, folder and files. I'd like to have different icons for open project, close project, open folder, close folders, and files
    but i got for the root which is a project object a folder icon and for folder when it is not expanded i got project icon and the when i expand it i got a folder icon, can someone help me please
    Here is my code :
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
         private Icon openIcon = null;
         private Icon closeIcon = null;
         private Icon leafIcon = null;
         private Icon projectOpenIcon = new ImageIcon("icons/book_open.png");
         private Icon projectCloseIcon = new ImageIcon("icons/book_blue.png");
         private Icon folderOpenIcon = new ImageIcon("icons/folder.png");
         private Icon folderCloseIcon = new ImageIcon("icons/folder_closed.png");
         private Icon fileIcon = new ImageIcon("icons/document.png");
         @Override
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                   boolean expanded, boolean leaf, int row, boolean hasFocus) {
              super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
                        hasFocus);
              LogescoTreeNode node =
                   (LogescoTreeNode)value;
              Object obj = node.getUserObject();
              System.out.println(obj.getClass().toString());
              if(openIcon == null) {
                   openIcon = this.getOpenIcon();
                   if(openIcon != null) {
                        if(obj instanceof LProject) {
                             openIcon = projectOpenIcon;
                             this.setOpenIcon(openIcon);
                             openIcon = null;
                        } else if(obj instanceof LFolder) {
                             openIcon = folderOpenIcon;
                             this.setOpenIcon(openIcon);     
                             openIcon = null;
              if(closeIcon == null) {
                   closeIcon = this.getClosedIcon();
                   if(closeIcon != null) {
                        if(obj instanceof LProject) {
                             closeIcon = projectCloseIcon;
                             this.setClosedIcon(closeIcon);
                             closeIcon = null;
                        } else if(obj instanceof LFolder) {
                             closeIcon = folderCloseIcon;
                             this.setClosedIcon(closeIcon);
                             closeIcon = null;
              this.setLeafIcon(fileIcon);
              return this;
    }Thank you.

    Hi all,
    I changed my code a bit knowing that the renderer is global to the tree so my (openIcon == null) is called only once for the first node.
    Here is my new code :
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
         private Icon projectOpenIcon = new ImageIcon("icons/book_open.png");
         private Icon projectCloseIcon = new ImageIcon("icons/book_blue.png");
         private Icon folderOpenIcon = new ImageIcon("icons/folder.png");
         private Icon folderCloseIcon = new ImageIcon("icons/folder_closed.png");
         private Icon fileIcon = new ImageIcon("icons/document.png");
         @Override
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                   boolean expanded, boolean leaf, int row, boolean hasFocus) {
              super.getTreeCellRendererComponent(tree, value, selected,
                        expanded, leaf, row, hasFocus);
              LogescoTreeNode node =
                   (LogescoTreeNode)value;
              Object obj = node.getUserObject();
              System.out.println(obj.getClass().toString());
              if(obj instanceof LProject) {
                   this.setIcon(expanded ? projectOpenIcon : projectCloseIcon);
              } else if(obj instanceof LFolder) {
                   this.setIcon(expanded ? folderOpenIcon : folderCloseIcon);
              } else {
                   this.setIcon(fileIcon);
              return this;
         }

  • How can i set different font for different tabs/pages

    I want to set different fonts for different tabs/pages?
    is it possible to do the same? If yes how?
    I can change the fonts under tools>options>contents>advanced. but that changes global settings.
    tried some add ons too- but that too changes the global settings.
    some pages like tweetdeck do not display icons etc properly under custom fonts.
    when i check "allow pages to select their own font" tweetdeck shows up fine but a number of other pages show fonts that are too big or some non standard fonts.
    Is there a way where i can select site default fonts for some sites/tabs, and custom fonts for other sites/tabs?
    otherwise i have to open different sites in different browsers- say i use my custom fonts- which apply globally, and open tweetdeck etc in Internet Explorer or Chrome etc. if i can have all tabs in one window/browser, that would be great.

    It's not a built-in feature to override a page's styles on a tab-by-tab or site-by-site basis, but perhaps someone has created an add-on for this?
    It also is possible to create style rules for particular sites and to apply them using either a userContent.css file or the Stylish extension. The Greasemonkey extension allows you to use JavaScript on a site-by-site basis, which provides further opportunity for customization. But these would take time and lots of testing to develop and perfect (and perfection might not be possible)...
    Regarding size, does the zoom feature help solve that part? In case you aren't familiar with the keyboard and mouse shortcuts for quickly changing the zoom level on a page, this article might be useful: [[Font size and zoom - increase the size of web pages]].

  • How to set different header for different Standard report page

    How to set different header for different Standard report page

    Hi,
    A easy answer would be use the 'set report header text.vi' but maybe you are talking about something else ?

  • HT1495 Can I set my iPad for different users? ie user - 1 login & user - 2 login

    Can I set my iPad for different users? ie user - 1 login &amp; user - 2 login

    Afraid not. The iPad is not intended for multiple users.

  • Can you set different sounds for different incoming email accounts?

    Can you set different sounds for different incoming email accounts? Example, I have multiple email accounts on Mail. I would like the sound for my roadrunner account to be different from my .mac and personal website accounts. Is it possible to configure this or is there a script out there that someone knows about.
    Thanks

    You could choose None in Preferences > General > New Mail Sound and set up a rule for each account in Preferences > Rules as follows:
    If [any/all] of the following conditions are met:
    [Account] [AccountName]
    Perform the following actions:
    [Play Sound] [Sound]
    Problem is, that would cause the sound to be played for junk mail as well — probably not what you want.

  • Setting different resolutions for different displays?, setting different resolutions for different displays?

    Hi,
    I have a 30" dell display that I have used with my MBP. I recently got a MBA and installed mountain lion.  One of the things they inexplicably removed was the ability in the menu bar to set different resolutions for different displays. The only way I can get my Dell Monitor to work is to use mirroring. But I don't want mirroring. I want two separate displays.  In Snow Leopard, the drop down display menu in the menu bar allowed you to pick different resolutions for different displays. Is there any possible way to do that in Mountain Lion?
    Tom

    Yes, assuming that the 8" display has a resolution that the Mac can support. When you open the Displays system preference, you'll get a settings window on each display (as long as the option for Mirroring isn't checked).
    Regards.

Maybe you are looking for

  • Arch64, RAM: 5gb of 6gb usable

    Hello there, i recently upgraded my hardware, adding 2x2GB Ram Sticks. Its a workstation (no laptop), The bios says that 6GB are Usable of 6GB Installed. (Before flashing it, it said only 5GB Usable). In Archlinux, i have only 5GB available free -m t

  • Problem when sorting data based on date

    I am trying to sort the following data based on the Transaction Receipt date column,unable to do it usi g the following syntax: <?sort:TRANSACTION_RECEIPT_DATE;'ascending';data-type='date'?> I have problem in converting the date in report to canonica

  • EJB Store called in a loop

    I am having a problem porting our application from weblogic5.1 (EJB1.1) to weblogic8.1 (EJB2.0) My current problem is an ejbStore called in a loop during a finder method call of a BMP entity bean. The outer session bean calls entity beans in a transa

  • No pdf file generated

    Hello, i use Acrobat XI Standard and i can't generate pdf-files from autocad in A0, A1 and A2 format via the pdf printer. I have created the user-defined page-layouts for the A0, A1 and A2 format, since these are not available as standard formats in

  • Pre_insert  and form trigger failure

    hi gurus, i'm adding security to a pre-insert trigger. if a user tries to insert something they shouldn't - the trigger fails. this is working. however, i want to somehow flush this record from the form. i cannot use clear_record, as its restricted f