SetSelection in JTree

hey,
im trying to set the selection of a particular node using the String name of the node, is it possible?
ive tried.
tree.setSelectionPath(new TreePath(
(DefaultMutableTreeNode)((Object)tableName)));throws all kinds of exceptions.
is there a way?
thanks.

hey,
ok if anyone is interested heres the function, couldnt get it to work without making it a void function, no explanation, but it works :
public void setNodeSelection(DefaultMutableTreeNode root, String tableName)
     if(root.getUserObject().toString().equalsIgnoreCase(tableName))
      tree.setSelectionPath(new TreePath(root.getPath()));
    for(int i = 0; i < root.getChildCount(); i++)
       DefaultMutableTreeNode tmp = (DefaultMutableTreeNode)root.getChildAt(i);
       if (tmp.getUserObject().toString().equalsIgnoreCase(tableName)) {
         tree.setSelectionPath(new TreePath(tmp.getPath()));
            return;
     DefaultMutableTreeNode next = root.getNextNode();
     if (next != null)
       setNodeSelection(next, tableName);
     else
       return;
// calling
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
          setNodeSelection(root, tableName);  // set selection of node and refresh table

Similar Messages

  • JarHelp

    Hi,
    I write down some code and done all process for embeding with oracle forms.
    when I run the form then show like this problem.
    unable to communicate with runtime process:
    code is some code is here:
    import java.io.*;
    import java.sql.*;
    import java.util.Vector;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class JTreeBoxPJC extends VBean
    static String loginId;
    private IHandler mHandler;
    private static final ID pSetTitle = ID.registerProperty("TREETEST");
    private static final ID pSetText = ID.registerProperty("SETTEXT");
    public JTreeBoxPJC()
              super();
              String[] strs = {"JavaGroup","Manjur","Reaz","Shamima","JTree","Kamal","Jamal"}; // 4
              CheckNode[] nodes = new CheckNode[strs.length];
              for (int i=0;i<strs.length;i++) {
              nodes[i] = new CheckNode(strs);
              nodes[0].add(nodes[1]);
              nodes[1].add(nodes[2]);
              nodes[1].add(nodes[3]);
              nodes[0].add(nodes[4]);
              nodes[4].add(nodes[5]);
              nodes[4].add(nodes[6]);
              nodes[3].setSelected(true);
              JTree tree = new JTree( nodes[0] );
              tree.setCellRenderer(new CheckRenderer());
              tree.getSelectionModel().setSelectionMode(
              TreeSelectionModel.SINGLE_TREE_SELECTION
              tree.putClientProperty("JTree.lineStyle", "Angled");
              tree.addMouseListener(new NodeSelectionListener(tree));
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    SwingUtilities.updateComponentTreeUI(this);
    catch(Exception exception)
    exception.printStackTrace();
    public void init(IHandler ihandler)
    super.init(ihandler);
    mHandler = ihandler;
    public boolean setProperty(ID id, Object obj)
    if(id == pSetTitle)
    loginId=(String)obj;
    JTreeBoxPJC tt=new JTreeBoxPJC();
    return true;
    }else if(id==pSetText) {
              loginId=(String)obj;
              JTreeBoxPJC tt=new JTreeBoxPJC();
              return true;
              }else{
                   return true;
    class NodeSelectionListener extends MouseAdapter {
    JTree tree;
    NodeSelectionListener(JTree tree) {
    this.tree = tree;
    public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    int row = tree.getRowForLocation(x, y);
    // TreePath path = tree.getPathForRow(row);
    TreePath path = tree.getSelectionPath();
    if (path != null) {
    CheckNode node = (CheckNode)path.getLastPathComponent();
    boolean isSelected = ! (node.isSelected());
    node.setSelected(isSelected);
    if (node.getSelectionMode() == CheckNode.DIG_IN_SELECTION) {
    if ( isSelected ) {
    tree.expandPath(path);
    } else {
    tree.collapsePath(path);
    ((DefaultTreeModel)tree.getModel()).nodeChanged(node);
    // I need revalidate if node is root. but why?
    if (row == 0) {
    tree.revalidate();
    tree.repaint();
    //Set_Custom_Property( 'BLOCK3.DIALOG', 1, 'CHECKBOXTREE', DFDF ) ;
    pls help me as early as possible.
    Manjur

  • Focus Problem with JTree and Menus

    Hi all,
    I have a problem with focus when editing a JTree and selecting a menu. The problem occurs when the user single clicks on a node, invoking the countdown to edit. If the user quickly clicks on a menu item, the focus will go to the menu item, but then when the countdown finishes, the node now has keyboard focus.
    Below is code to reproduce the problem. Click on the node, hover for a little bit, then quickly click on the menu item.
    How would I go about fixing the problem? Thanks!
    import java.awt.Container;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class MyTree extends JTree {
         public MyTree(DefaultTreeModel treemodel) {
              setModel(treemodel);
              setRootVisible(true);
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JMenuBar bar = new JMenuBar();
              JMenu menu = new JMenu("Test");
              JMenuItem item = new JMenuItem("Item");
              menu.add(item);
              bar.add(menu);
              frame.setJMenuBar(bar);
              Container contentPane = frame.getContentPane();
              contentPane.setLayout(new GridLayout(1, 2));
              DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("Root");
              root1.add(new DefaultMutableTreeNode("Root2"));
              DefaultTreeModel model = new DefaultTreeModel(root1);
              MyTree tree1 = new MyTree(model);
              tree1.setEditable(true);
              tree1.setCellEditor(
                   new ComponentTreeCellEditor(
                        tree1,
                        new ComponentTreeCellRenderer()));
              tree1.setRowHeight(0);
              contentPane.add(tree1);
              frame.pack();
              frame.show();
    import java.awt.FlowLayout;
    import java.util.EventObject;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    public class ComponentTreeCellEditor
         extends DefaultTreeCellEditor
         implements TreeCellEditor {
         private String m_oldValue;
         private TreeCellRenderer m_renderer = null;
         private DefaultTreeModel m_model = null;
         private JPanel m_display = null;
         private JTextField m_field = null;
         private JTree m_tree = null;
         public ComponentTreeCellEditor(
              JTree tree,
              DefaultTreeCellRenderer renderer) {
              super(tree, renderer);
              m_renderer = renderer;
              m_model = (DefaultTreeModel) tree.getModel();
              m_tree = tree;
              m_display = new JPanel(new FlowLayout(FlowLayout.LEFT));
              m_field = new JTextField();
              m_display.add(new JLabel("My Label "));
              m_display.add(m_field);
         public java.awt.Component getTreeCellEditorComponent(
              JTree tree,
              Object value,
              boolean isSelected,
              boolean expanded,
              boolean leaf,
              int row) {
              m_field.setText(value.toString());
              return m_display;
         public Object getCellEditorValue() {
              return m_field.getText();
          * The edited cell should always be selected.
          * @param anEvent the event that fired this function.
          * @return true, always.
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
          * Only edit immediately if the event is null.
          * @param event the event being studied
          * @return true if event is null, false otherwise.
         protected boolean canEditImmediately(EventObject event) {
              return (event == null);
    }

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Problem with Jtree and a checkbox

    Hello,
    I have a problem with my tree implementation.
    I create a tree and i want to add a checkbox in each node.
    this is my code :
    DefaultMutableTreeNode root;
    root = new DefaultMutableTreeNode(new JCheckBox());
    DefaultTreeModel model = new DefaultTreeModel(root);
    _tree = new JTree(model);
    eastpane.add(tree);
    THe problem is that my checkbox doesn't appear. And a message appears
    instead of my checkbox.
    But my tree appears.
    Can anyone help me .
    Thanks

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Problemns with JTree

    Hi! I'm having problems with the Tree cell renderer. I must render a tree that have leafs that is also JPanels compounded by a checkbox, an icon and a the text label. It's supposed to alter the state of the checkbox when clicked or when press the spacebar over the cell, but it isn't working...
    If I set the tree as editable (down in the code, in main method), the checkbox is selected only after the second click, but the cell is not being highlighted and cannot collapse the category nodes. Otherwise, when set the Tree as NOT editable, the highlight of cell and the rest works, but obviously I cannot edit the checkboxes...
    Can someone help me, please?
    package test;
    import com.interact.sas.ResourceLocator;
    import com.interact.sas.dms.*;
    import com.interact.sas.ui.UserIconLabel;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.tree.*;
    public class DocumentControllerTreeTest
        static class MyTreeCellEditor extends AbstractCellEditor implements TreeCellEditor, TreeCellRenderer
            private static Icon iconCategory = ResourceLocator.getIcon( "sas/dms/tb_categories.png" );
            private static Border noFocusBorder = new EmptyBorder( 1, 1, 1, 1 );
            private JPanel cell = new JPanel();
            private JCheckBox checkRequired = new JCheckBox();
            private UserIconLabel userIconLabel = new UserIconLabel();
            private DocumentControllerTree.Item currentItem = null;
            public MyTreeCellEditor()
                userIconLabel.setOpaque( false );
                checkRequired.setOpaque( false );
                cell.setLayout( new BorderLayout() );
                cell.add( checkRequired, BorderLayout.WEST );
                cell.add( userIconLabel, BorderLayout.CENTER );
                cell.addKeyListener( new KeyAdapter()
                    public void keyPressed( KeyEvent e )
                        if ( e.getKeyCode() == KeyEvent.VK_SPACE )
                            checkRequired.setSelected( ! checkRequired.isSelected() );
                            e.consume();
                cell.addMouseListener( new java.awt.event.MouseAdapter()
                    public void mouseClicked(java.awt.event.MouseEvent evt)
                        checkRequired.setSelected( ! checkRequired.isSelected() );
             * getCellEditorValue
             * @return Object
            public Object getCellEditorValue()
                currentItem.getController().setRequired( checkRequired.isSelected() );
                return new Boolean( currentItem.getController().isRequired() );
             * getTreeCellEditorComponent
             * @param JTree tree,
             * @param Object value,
             * @param boolean isSelected,
             * @param boolean expanded,
             * @param boolean leaf,
             * @param int row
             * @return Component
            public Component getTreeCellEditorComponent( JTree tree,
                    Object value,
                    boolean isSelected,
                    boolean expanded,
                    boolean leaf,
                    int row)
                return getTreeCellRendererComponent( tree, value, isSelected, expanded, leaf, row, true );
             * getTreeCellRendererComponent
             * @param JTree tree,
             * @param Object value,
             * @param boolean selected,
             * @param boolean expanded,
             * @param boolean leaf,
             * @param int row,
             * @param boolean hasFocus
             * @return Component
            public Component getTreeCellRendererComponent( JTree tree,
                    Object value,
                    boolean isSelected,
                    boolean isExpanded,
                    boolean isLeaf,
                    int row,
                    boolean hasFocus )
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object object = node.getUserObject();
                if ( object instanceof DocumentControllerTree.Item )
                    currentItem = (DocumentControllerTree.Item) object;
                    checkRequired.setSelected( currentItem.getController().isRequired() );
                    //checkRequired.setSelected( !checkRequired.isSelected() );
                    int action = currentItem.getController().getAction();
                    if ( action == DocumentController.ACTION_APROVE ||
                            action == DocumentController.ACTION_VERIFY )
                        checkRequired.setVisible( true );
                    else
                        checkRequired.setVisible( false );
                    userIconLabel.setFont( tree.getFont() );
                    userIconLabel.setUser( currentItem.getUser() );
                    userIconLabel.setText( currentItem.getUser().getName() );
                else
                    // nunca poderia chegar aqui ...
                    checkRequired.setVisible( false );
                    userIconLabel.setFont( tree.getFont() );
                    userIconLabel.setIcon( ! isLeaf ? iconCategory : null );
                    userIconLabel.setText( object.toString() );
                if ( isSelected )
                    cell.setBackground( UIManager.getColor( "Tree.selectionBackground") );
                    cell.setForeground( UIManager.getColor( "Tree.selectionForeground") );
                else
                    cell.setBackground( tree.getBackground() );
                    cell.setForeground( tree.getForeground() );
                Border border = noFocusBorder;
                if (hasFocus)
                    if (isSelected)
                        border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
                    if (border == null)
                        border = UIManager.getBorder("List.focusCellHighlightBorder");
                cell.setBorder(border);
                return cell;
        public static void main( String[] args )
            try
                DocumentControllerTree tree = new DocumentControllerTree();
                DocumentManager dm = DocumentManager.getInstance();
                DocumentCategory dc = dm.getCategory( 32 );
                Vector<DocumentController> vdc = dm.getControllers( dc );
                tree.setCellRenderer( new MyTreeCellEditor() );
                tree.setCellEditor( new MyTreeCellEditor() );
                tree.setCategory( dc );
                tree.setControllers( vdc );
                // This must be true
                //tree.setEditable( true );
                JScrollPane scroller = new JScrollPane( tree );
                scroller.setPreferredSize( new Dimension( 240, 320 ) );
                JOptionPane.showMessageDialog( null, scroller );
            catch ( Exception e )
                e.printStackTrace();
            System.exit( 0 );
    }

    OK, here's briefly what I'd do:
    1
    In your tree constructor, set a custom TreeCellRenderer. (I assume your tree extends JTree.)
    2
    Create a custom TreeCellRenderer by extending JPanel and implementing TreeCellRenderer. In the getTreeCellRendererComponent method, remember you don't have to use a component that you have around. You use the tree node's text: tree.convertValueToText(value, sel, expanded, leaf, row, hasFocus)); This returns a string. The string could be "true" or "false". You then create a JCheckBox based on this value. Add the JCheckBox to �this�, i.e. to the custom TreeCellRenderer that extends a JPanel. Return �this�. Remember that once �this� is returned, the value is forgotten and the JCheckBox is unclickable. (What you click actually is the TreeCellRenderer, that then decides you want to focus a node and thereafter passes focus and subsequent clicks to your panel and/or the TreeCellEditor).
    3
    Back to the tree constructor. Set your TreeCellEditor to a custom class of yours. Copy the code from DefaultCellEditor. There is a constructor in DefaultCellEditor that accepts a JCheckBox as sole argument. Try that one. In an inner class in DefaultCellEditor, EditorDelegate, you'll find the stopCellEditing method. Override it and make sure to convert boolean values back to "true" or "false" in the tree node, so that the renderer will have the right value to work with.
    From there on, I guess things should work by themselves. (Warning: completely unchecked!!!) If not, at least the code is sufficiently separated for us to know where it fails (renderer, editor, tree...)
    PS. Second thought: DefaultMutableTreeNode accepts an Object as object, not only a string. Maybe you could use a boolean value or a Boolean object directly in the tree node instead of strings...
    Just my 2 cents

  • JCheckBox as nodes in JTree having problems with custom renderer and editor

    Ok, let me give some background. I have an XML document that I am parsing and reading in as a JTree. Works fine.
    Next, I have overwritten the DefaultTreeCellEditor to return a JCheckBox and in this implementation of the getTreeCellEditorComponent(), I actually tell the node that he is selected. Works great.
    Next, I have overwritten the DefaultTreeCellRenderer to return a JCheckBox and in the implementation of the getTreeCellEditorComponenet, I actually check to see if the Node is selected in the tree based upon the isSelected state of the actual Tree Node set in the tree cell editor, and if so, I set the JCheckBox to selected(true).Works Great.
    Now, here is the issue. If a node in the tree is selected that contains children, then I want all of the children of that node to also be selected. However, when I select a node with children only the selected node is changed, and then a few moments later, the system repaints the entire tree and ALL nodes int the tree are set to a selected state. Strange? Yes. Any ideas?? WONDERFUL!! :)
    Here is the TreeCellEditor code:
    public Component getTreeCellEditorComponent(JTree tree,
    Object value,
    boolean isSelected,
    boolean expanded,
    boolean leaf,
    int row)
    elementCheckBox_ = new JCheckBox();
    Component result = null;
    System.out.println("isSelected? Editor = " + isSelected);
    TreePath newPath = tree.getPathForRow(row);
    System.out.println("value = " + value.getClass().toString());
    if(value instanceof IMarketTreeNodeElement)
    if(isSelected)
    if(((IMarketTreeNodeElement)value).isSelected())
    ((IMarketTreeNodeElement)value).setSelected(false);
    else
    ((IMarketTreeNodeElement)value).setSelected(true);
    elementCheckBox_.setSelected(isSelected);
    return elementCheckBox_;
    Here is the TreeCellRenderer code:
    public Component getTreeCellRendererComponent(JTree tree,
    Object value,
    boolean selected,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus)
    Color colSelBorderCol = UIManager.getColor
    ("Tree.selectionBorderColor");
    selBorder_ = BorderFactory.createLineBorder(colSelBorderCol, 1);
    normBorder_ = BorderFactory.createEmptyBorder(1,1,1,1);
    elementCheckBox_.setText(value.toString());
    if(selected)
    elementCheckBox_.setSelected(selected);
    elementCheckBox_.setForeground(Color.YELLOW);
    elementCheckBox_.setBackground(Color.RED);
    else
    elementCheckBox_.setForeground(tree.getForeground());
    elementCheckBox_.setBackground(tree.getBackground());
    if (hasFocus)
    elementCheckBox_.setBorder(selBorder_);
    else
    elementCheckBox_.setBorder(normBorder_);
    return elementCheckBox_;
    Here is the Node Code setting all child nodes to selected:
    public void setSelected(boolean selected)
    isSelected_ = selected;
    if(isSelected_)
    if((this.getTagName() == "MARKET") ||
    (this.getTagName() == "TIER") &&
    (this.getChildCount() != 0))
    selectChildren(true);
    else
    if((this.getTagName() == "MARKET") ||
    (this.getTagName() == "TIER") &&
    (this.getChildCount() != 0))
    selectChildren(false);
    public boolean isSelected()
    return isSelected_;
    public void selectChildren(boolean selected)
    int children = getChildCount();
    for(int i = 0; i < children; i++)
    IMarketTreeNodeElement elem = (IMarketTreeNodeElement)
    this.getChildNodes().item(i);
    isSelected_ = selected;
    Thanks for any help! :-)

    I tried to run your sample code and it won't compile. The header files:
    #include
    #include
    #include
    #include
    #include
    do not exist on my install of MeasurementStudio. I am a bit suspicous that I don't have the latest and greatest (loading the dialong resouce gave version warnings). Here is one of my header file headers:
    //==============================================================================
    // Title : NiAxes3d.h
    // Copyright : National Instruments 1999. All Rights Reserved.
    // Purpose : Defines the CNiAxes3D class.
    //==============================================================================
    I
    looked on your updates site and don't really see an update that applies to ComponentWorks or MeasurementStudio. My version per the MAX program for 3DControls is 3.5.549.
    Do I need a newer version? What do I have to do to get the updated version? What does it cost?
    Chuck

  • Jtree Select node and change leafs icon problem

    Hi All,
    i create a tree and implement a TreeSelectionListener:
    my mission is whenever i select a node i need to change the icon of this node (for now.later i will have to find if it have childrens).
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    public class TreeView{
         DefaultMutableTreeNode top;
         JTree tree ;
         Color frameColor;
         public static ImageIcon NoTSelIcon;
         public static ImageIcon SelIcon;
        public static String[] name= new String[8];
         public TreeView(Color BackColor) {
              // TODO Auto-generated constructor stub
            top =  new DefaultMutableTreeNode("Diagnostics");
            this.frameColor=BackColor;
             SelIcon = createImageIcon("../Resource/Images/Select.gif");
             if (SelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
             NoTSelIcon = createImageIcon("../Resource/Images/NotSelc.gif");
               if (NoTSelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
         public Component createTreeComponents(){
                //Create the nodes.
                 createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            //TREE LISTENERS
            //Treeselction listener
            Handler hObject = new Handler();
            tree.addTreeSelectionListener(hObject);
           //Tree expand/collapse listener
            HandlerExpansionListener hObjectExpan = new HandlerExpansionListener();
            tree.addTreeExpansionListener(hObjectExpan);
    //       tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
            //set tree background
            tree.setBackground(frameColor);
             tree.setCellRenderer(new OverrideTreeCellRenderer(frameColor,SelIcon,NoTSelIcon));
            return tree;
          private void createNodes(DefaultMutableTreeNode top) {
                 DefaultMutableTreeNode category = null;
                 DefaultMutableTreeNode SubCategory = null;
                 DefaultMutableTreeNode SubCategoryBasee = null;
                 DefaultMutableTreeNode SubSubCategoryBasee = null;
                 category = new DefaultMutableTreeNode("Dfe");
                 top.add(category);
                 //Sub test visible
                 SubCategory = new DefaultMutableTreeNode("Test Visible");
                 category.add(SubCategory);
                 SubCategory.add(new DefaultMutableTreeNode("Son 1"));
                 SubCategory.add(new DefaultMutableTreeNode("Son 2"));
                 SubSubCategoryBasee = new DefaultMutableTreeNode("Test Base");
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 1"));
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 2"));
                 SubCategory.add(SubSubCategoryBasee);
          class Handler implements TreeSelectionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeSelect event ");
                        TreePath trph;
                        trph=arg0.getNewLeadSelectionPath();
                        int count=trph.getPathCount();
                        DefaultMutableTreeNode Selnode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                        String Name = (String)Selnode.getUserObject();
                        setSelected(Selnode,true);
                        int number_ofnodes=getNodeCountBelow((TreeModel)tree.getModel() , Selnode, false);
                        System.out.println("The Number of nodes under "+Name+"="+number_ofnodes);
                        tree.setCellRenderer(new IconRenderer(SelIcon,NoTSelIcon,frameColor));
          class HandlerExpansionListener implements TreeExpansionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)  tree.getLastSelectedPathComponent();
                        if (node == null) return;
                      }     // The inner class
                   public void treeCollapsed(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeCollapsed event ");
                   public void treeExpanded(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeExpanded event ");
          /** Returns an ImageIcon, or null if the path was invalid. */
             protected static ImageIcon createImageIcon(String path) {
                  //ImageIcon imcon= new ImageIcon(path);
                  //return imcon;
                 java.net.URL imgURL = TreeView.class.getResource(path);
                 if (imgURL != null) {
                     return new ImageIcon(imgURL);
                 } else {
                     System.err.println("Couldn't find file: " + path);
                     return null;
             DefaultMutableTreeNode newnode;
             public void setSelected(DefaultMutableTreeNode Selnode ,boolean isSelected)
                    Enumeration Enchilds=Selnode.children();//ENUMRATE ALL CHILDS FOR THIS NODE
                 if (Enchilds != null)
                      while (Enchilds.hasMoreElements())
                           newnode=(DefaultMutableTreeNode)Enchilds.nextElement();
                           String NameSel = (String)newnode.getUserObject();
                           setSelected(newnode,isSelected);
             //GETTING THE TREE DEPTH
             public int getNodeCountBelow(TreeModel model, Object node, boolean includeInitialNode)
                 int n = includeInitialNode ? 1 : 0;
                 for (int i = 0; i < model.getChildCount(node); i ++)
                     n += getNodeCountBelow(model, model.getChild(node, i), true);
                 return n;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import javax.swing.Icon;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class IconRenderer extends DefaultTreeCellRenderer {
         private static final long serialVersionUID = 1L;
         Icon SelectedIcon;
         Icon NotSelectedIcon;
         Color BackgroundColor;
         boolean Selected=false;
         boolean Leaf=false;
         boolean IsItaChild=false;
         DefaultMutableTreeNode SelctedNode=null;
        public IconRenderer(Icon SelIcon,Icon NoTSelIcon,Color Bacground) {
             SelectedIcon = SelIcon;
             NotSelectedIcon = NoTSelIcon;
             BackgroundColor=Bacground;
             setBackgroundNonSelectionColor(BackgroundColor);
        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);
             Selected=sel;
             Leaf=leaf;
             DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
             String s2 = (String)node.getUserObject();
       return this;
    }my problem is :
    when i select a node the the method "getTreeCellRendererComponent"
    start to run on the entire tree from buttom to top and than from top to buttom.
    for me it waste of time because if has say 100 nodes it wont botthers me.
    but i have 20000 nodes and more its take a time.
    and for all this nodes i have to make compares.
    is there a way to force the DefaultTreeCellRenderer to not run the entire tree???
    Thanks

    You need to make sure that your TreeModel interprets your group nodes to be non-leaf nodes (one of the methods in the TreeModel interface is called isLeaf). If you are using a DefaultTreeModel with DefaultMutableTreeNode objects, you can use the askAllowsChildren property of DefaultTreeModel and the allowsChildren property of DefaultMutableTreeNode to control this. See the API for more details:
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html

  • Selcting Multiple  CheckBoxe in a JTREE without holding CTRL / SHIFT

    HI,
    My JTree is having JCheckBOxes as nodes .... Now the problem is i want to select multiple nodes (checkboxes) with out holding CTRL/SHIFT key .
    Please help regarding this issue ..
    The code of my renderer class is as below:
    * MyTreeRendered.java
    * Created on April 27, 2006, 7:42 PM
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class MyTreeRendered extends DefaultTreeCellRenderer  {
        private JCheckBox cb ;
        /** Creates a new instance of MyTreeRendered */
        public MyTreeRendered() {
        public Component getTreeCellRendererComponent(
                            JTree tree,
                            Object value,
                            boolean sel,
                            boolean expanded,
                            boolean leaf,
                            int row,
                            boolean hasFocus){
           if(cb == null) {
               cb = new JCheckBox();
               cb.setBackground(tree.getBackground());
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
           cb.setText(node.getUserObject().toString());
           cb.setSelected(sel);
           return cb;
    }

    These are the methods which seem to define that behaviour:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicTreeUI.html#isToggleSelectionEvent(java.awt.event.MouseEvent)
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicTreeUI.html#isMultiSelectEvent(java.awt.event.MouseEvent)
    You'd have to write your own TreeUI and override them.

  • Selection Of checkbox in the JTree

    Hi all,
    I have a very small problem in JTree.
    The JTree is with checkbox.When ever I select on the node the simultaneous chechbox is selected.
    But some time with the same operation the checkbox is not selected.
    Here,I attache the part of code which is responsible for my problem.
    public void mouseClickedNodeSelectionListener(MouseEvent e)
            int x = e.getX();
            int y = e.getY();
            int row = tree.getRowForLocation(x, y);
            TreePath path = tree.getPathForRow(row);
            //TreePath path = tree.getSelectionPath();
            if (path != null) {
                if(/*e.getClickCount()==1 &&*/ ElmsConstants.isDoubleClicked)
                    if(lastPath!=null)
                        tree.setSelectionPath(lastPath);
                    return;
                lastPath = path;
                CheckNode node = (CheckNode) path.getLastPathComponent();
                int selectedId = 0;
                if(node.getElmsData()!=null)
                    selectedId = (node.getElmsData().getId()).intValue();
                if(lastSelectedId==selectedId)
                    boolean isSelected = !(node.isSelected());
                    node.setSelected(isSelected);
                    tree.updateUI();
                    ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
                    if (row == 0) {
                        try{
                            tree.revalidate();
                            tree.repaint();
                        }catch(Exception eE)
                            System.out.println("Exception in Tree repaint");
                lastSelectedId=selectedId;
    }Any Body Please help me.
    Thank you,
    Ananda

    It's hard to say what's the problem when you post this little code.
    But probably the problem is that you're listening for mouse click event.
    This event only fires when you click the mouse without moving it.
    If by mistake you move the mouse while you click it you will not get a mouse click event.
    You can use the mousePressed or mouseReleased events instead.
    Anyway I would implement this with a custom editor instead of listening to mouse events.
    See example here: [http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm]

  • Checkbox with JTree

    hai,
    i added checkbox to each tree node and my coding is
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.KeyStroke;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    /** Provides checkbox-based selection of tree nodes. Override the protected
    * methods to adapt this renderer's behavior to your local tree table flavor.
    * No change listener notifications are provided.
    public class CheckBoxTreeCellRenderer implements TreeCellRenderer {
    public static final int UNSELECTABLE = 0;
    public static final int FULLSELECTED = 1;
    public static final int NOTSELECTED = 2;
    public static final int PARTIALSELECTED = 3;
    private TreeCellRenderer renderer;
    public static JCheckBox checkBox;
    private Point mouseLocation;
    private int mouseRow = -1;
    private int pressedRow = -1;
    private boolean mouseInCheck;
    private int state = NOTSELECTED;
    private Set checkedPaths;
    private JTree tree;
    private MouseHandler handler;
    /** Create a per-tree instance of the checkbox renderer. */
    public CheckBoxTreeCellRenderer(JTree tree, TreeCellRenderer original) {
    this.tree = tree;
    this.renderer = original;
    checkedPaths = new HashSet();
    checkBox = new JCheckBox();
    checkBox.setOpaque(false);
    System.out.println(checkBox.isSelected());
    checkBox.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              trace(checkBox);
    // ActionListener actionListener = new ActionListener() {
    // public void actionPerformed(ActionEvent actionEvent) {
    // AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
    // boolean selected = abstractButton.getModel().isSelected();
    // System.out.println(selected);
    // // abstractButton.setText(newLabel);
    // checkBox.addActionListener(new ActionListener(){
    //               public void actionPerformed(ActionEvent actionEvent) {
    //                    Checkbox cb = actionEvent.getSource();
    //     boolean selected = abstractButton.getModel().isSelected();
    //     System.out.println(selected);
    checkBox.setSize(checkBox.getPreferredSize());
    private static void trace(JCheckBox cb) {
         if (cb.isSelected())
              System.out.println(cb.getText()+" is " + cb.isSelected());
         else
              System.out.println(cb.getText()+" is " + cb.isSelected());
    protected void installMouseHandler() {
    if (handler == null) {
    handler = new MouseHandler();
    addMouseHandler(handler);
    protected void addMouseHandler(MouseHandler handler) {
    tree.addMouseListener(handler);
    tree.addMouseMotionListener(handler);
    private void updateMouseLocation(Point newLoc) {
    if (mouseRow != -1) {
    repaint(mouseRow);
    mouseLocation = newLoc;
    if (mouseLocation != null) {
    mouseRow = getRow(newLoc);
    repaint(mouseRow);
    else {
    mouseRow = -1;
    if (mouseRow != -1 && mouseLocation != null) {
    Point mouseLoc = new Point(mouseLocation);
    Rectangle r = getRowBounds(mouseRow);
    if (r != null)
    mouseLoc.x -= r.x;
    mouseInCheck = isInCheckBox(mouseLoc);
    else {
    mouseInCheck = false;
    protected int getRow(Point p) {
    return tree.getRowForLocation(p.x, p.y);
    protected Rectangle getRowBounds(int row) {
    return tree.getRowBounds(row);
    protected TreePath getPathForRow(int row) {
    return tree.getPathForRow(row);
    protected int getRowForPath(TreePath path) {
    return tree.getRowForPath(path);
    public void repaint(Rectangle r) {
    tree.repaint(r);
    public void repaint() {
    tree.repaint();
    private void repaint(int row) {
    Rectangle r = getRowBounds(row);
    if (r != null)
    repaint(r);
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    installMouseHandler();
    TreePath path = getPathForRow(row);
    state = UNSELECTABLE;
    if (path != null) {
    if (isChecked(path)) {
    state = FULLSELECTED;
    else if (isPartiallyChecked(path)) {
    state = PARTIALSELECTED;
    else if (isSelectable(path)) {
    state = NOTSELECTED;
    checkBox.setSelected(state == FULLSELECTED);
    checkBox.getModel().setArmed(mouseRow == row && pressedRow == row && mouseInCheck);
    checkBox.getModel().setPressed(pressedRow == row && mouseInCheck);
    checkBox.getModel().setRollover(mouseRow == row && mouseInCheck);
    Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
    checkBox.setForeground(c.getForeground());
    if (c instanceof JLabel) {
    JLabel label = (JLabel)c;
    // Augment the icon to include the checkbox
    Icon customOpenIcon = new ImageIcon("browse.gif");
    label.setIcon(new CompoundIcon(label.getIcon()));
    return c;
    private boolean isInCheckBox(Point where) {
    Insets insets = tree.getInsets();
    int right = checkBox.getWidth();
    int left = 0;
    if (insets != null) {
    left += insets.left;
    right += insets.left;
    return where.x >= left && where.x < right;
    public boolean isExplicitlyChecked(TreePath path) {
    return checkedPaths.contains(path);
    /** Returns whether selecting the given path is allowed. The default
    * returns true. You should return false if the given path represents
    * a placeholder for a node that has not yet loaded, or anything else
    * that doesn't represent a normal, operable object in the tree.
    public boolean isSelectable(TreePath path) {
    return true;
    /** Returns whether the given path is currently checked. */
    public boolean isChecked(TreePath path) {
    if (isExplicitlyChecked(path)) {
    return true;
    else {
    if (path.getParentPath() != null) {
    return isChecked(path.getParentPath());
    else {
    return false;
    public boolean isPartiallyChecked(TreePath path) {
    Object node = path.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath childPath = path.pathByAddingChild(child);
    if (isChecked(childPath) || isPartiallyChecked(childPath)) {
    return true;
    return false;
    private boolean isFullyChecked(TreePath parent) {
    Object node = parent.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath childPath = parent.pathByAddingChild(child);
    if (!isExplicitlyChecked(childPath)) {
    return false;
    return true;
    public void toggleChecked(int row) {
    TreePath path = getPathForRow(row);
    boolean isChecked = isChecked(path);
    removeDescendants(path);
    if (!isChecked) {
    checkedPaths.add(path);
    setParent(path);
    repaint();
    private void setParent(TreePath path) {
    TreePath parent = path.getParentPath();
    if (parent != null) {
    if (isFullyChecked(parent)) {
    removeChildren(parent);
    checkedPaths.add(parent);
    } else {
    if (isChecked(parent)) {
    checkedPaths.remove(parent);
    addChildren(parent);
    checkedPaths.remove(path);
    setParent(parent);
    private void addChildren(TreePath parent) {
    Object node = parent.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath path = parent.pathByAddingChild(child);
    checkedPaths.add(path);
    private void removeChildren(TreePath parent) {
    for (Iterator i = checkedPaths.iterator(); i.hasNext();) {
    TreePath p = (TreePath) i.next();
    if (p.getParentPath() != null && parent.equals(p.getParentPath())) {
    i.remove();
    private void removeDescendants(TreePath ancestor) {
    for (Iterator i = checkedPaths.iterator(); i.hasNext();) {
    TreePath path = (TreePath) i.next();
    if (ancestor.isDescendant(path)) {
    i.remove();
    /** Returns all checked rows. */
    public int[] getCheckedRows() {
    TreePath[] paths = getCheckedPaths();
    int[] rows = new int[checkedPaths.size()];
    for (int i = 0; i < checkedPaths.size(); i++) {
    rows[i] = getRowForPath(paths);
    Arrays.sort(rows);
    return rows;
    /** Returns all checked paths. */
    public TreePath[] getCheckedPaths() {
    return (TreePath[]) checkedPaths.toArray(new TreePath[checkedPaths.size()]);
    protected class MouseHandler extends MouseAdapter implements MouseMotionListener {
    public void mouseEntered(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mouseExited(MouseEvent e) {
    updateMouseLocation(null);
    public void mouseMoved(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mouseDragged(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mousePressed(MouseEvent e) {
    pressedRow = e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK
    ? getRow(e.getPoint()) : -1;
    updateMouseLocation(e.getPoint());
    public void mouseReleased(MouseEvent e) {
    if (pressedRow != -1) {
    int row = getRow(e.getPoint());
    if (row == pressedRow) {
    Point p = e.getPoint();
    Rectangle r = getRowBounds(row);
    p.x -= r.x;
    if (isInCheckBox(p)) {
    toggleChecked(row);
    pressedRow = -1;
    updateMouseLocation(e.getPoint());
    public void mouseClicked(MouseEvent e){
         if(checkBox.isSelected()){
              System.out.println(checkBox.getName());
    /** Combine a JCheckBox's checkbox with another icon. */
    private final class CompoundIcon implements Icon {
    private final Icon icon;
    private final int w;
    private final int h;
    private CompoundIcon(Icon icon) {
    if (icon == null) {
    icon = new Icon() {
    public int getIconHeight() { return 0; }
    public int getIconWidth() { return 0; }
    public void paintIcon(Component c, Graphics g, int x, int y) { }
    this.icon = icon;
    this.w = icon.getIconWidth();
    this.h = icon.getIconHeight();
    public int getIconWidth() {
    return checkBox.getPreferredSize().width + w;
    public int getIconHeight() {
    return Math.max(checkBox.getPreferredSize().height, h);
    public void paintIcon(Component c, Graphics g, int x, int y) {
    if (c.getComponentOrientation().isLeftToRight()) {
    int xoffset = checkBox.getPreferredSize().width;
    int yoffset = (getIconHeight()-icon.getIconHeight())/2;
    icon.paintIcon(c, g, x + xoffset, y + yoffset);
    if (state != UNSELECTABLE) {
    paintCheckBox(g, x, y);
    else {
    int yoffset = (getIconHeight()-icon.getIconHeight())/2;
    icon.paintIcon(c, g, x, y + yoffset);
    if (state != UNSELECTABLE) {
    paintCheckBox(g, x + icon.getIconWidth(), y);
    private void paintCheckBox(Graphics g, int x, int y) {
    int yoffset;
    boolean db = checkBox.isDoubleBuffered();
    checkBox.setDoubleBuffered(false);
    try {
    yoffset = (getIconHeight()-checkBox.getPreferredSize().height)/2;
    g = g.create(x, y+yoffset, getIconWidth(), getIconHeight());
    checkBox.paint(g);
    if (state == PARTIALSELECTED) {
    final int WIDTH = 2;
    g.setColor(UIManager.getColor("CheckBox.foreground"));
    Graphics2D g2d = (Graphics2D)g;
    g2d.setStroke(new BasicStroke(WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int w = checkBox.getWidth();
    int h = checkBox.getHeight();
    g.drawLine(w/4+2, h/2-WIDTH/2+1, w/4+w/2-3, h/2-WIDTH/2+1);
    g.dispose();
    finally {
    checkBox.setDoubleBuffered(db);
    private static String createText(TreePath[] paths) {
    if (paths.length == 0) {
    return "Nothing checked";
    String checked = "Checked:\n";
    for (int i=0;i < paths.length;i++) {
    checked += paths[i] + "\n";
    return checked;
    public static void main(String[] args) {
    try {
    final String SWITCH = "toggle-componentOrientation";
    try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e1) {
                   e1.printStackTrace();
              } catch (InstantiationException e1) {
                   e1.printStackTrace();
              } catch (IllegalAccessException e1) {
                   e1.printStackTrace();
              } catch (UnsupportedLookAndFeelException e1) {
                   e1.printStackTrace();
    JFrame frame = new JFrame("Tree with Check Boxes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final DefaultMutableTreeNode a = new DefaultMutableTreeNode("Node 1");
    for(int i =0 ; i<3; i++ ){
         DefaultMutableTreeNode b = new DefaultMutableTreeNode("ChildNode "+i);
         a.add(b);
    DefaultMutableTreeNode e = new DefaultMutableTreeNode("Node 2");
    for(int i =0 ; i<3; i++ ){
         DefaultMutableTreeNode f = new DefaultMutableTreeNode("ChildNode "+i);
         e.add(f);
    DefaultMutableTreeNode al = new DefaultMutableTreeNode("Sample");
    al.add(a);
    al.add(e);
    final JTree tree = new JTree(al);
    final CheckBoxTreeCellRenderer r =
    new CheckBoxTreeCellRenderer(tree, tree.getCellRenderer());
    tree.setCellRenderer(r);
    int rc = tree.getRowCount();
    tree.getActionMap().put(SWITCH, new AbstractAction(SWITCH) {
    public void actionPerformed(ActionEvent e) {
    ComponentOrientation o = tree.getComponentOrientation();
    if (o.isLeftToRight()) {
    o = ComponentOrientation.RIGHT_TO_LEFT;
    else {
    o = ComponentOrientation.LEFT_TO_RIGHT;
    tree.setComponentOrientation(o);
    tree.repaint();
    int mask = InputEvent.SHIFT_MASK|Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_O, mask), SWITCH);
    final JTextArea text = new JTextArea(createText(r.getCheckedPaths()));
    text.setPreferredSize(new Dimension(200, 100));
    tree.addMouseListener(new MouseAdapter() {
    public void mouseReleased(MouseEvent e) {
    // Invoke later to ensure all mouse handling is completed
    SwingUtilities.invokeLater(new Runnable() { public void run() {
    text.setText(createText(r.getCheckedPaths()));
    JScrollPane pane = new JScrollPane(tree);
    frame.getContentPane().add(pane);
    // frame.getContentPane().add(new JScrollPane(text), BorderLayout.SOUTH);
    frame.pack();
    frame.setSize(600,400);
    frame.setVisible(true);
    catch(Exception e) {
    e.printStackTrace();
    System.exit(1);
    now i need to get nodes names which has been selected, how can i do this
    can anyone help me ...
    regards,
    shobi

    Also, use code tags and post a SSCCE -- I'm sure more of your posted code is irrelevant to your question and few people are going to look at a code listing that long.
    [http://mindprod.com/jgloss/sscce.html]

  • JCheckBox used in a JTree Displaying Wrong

    I have a class that creates a JTree and sets the node to a JCheckBox. The checkboxes appear fine except for the fact that instead of the JCheckBoX name appearing next to the actual checkbox the JCheckBox values appear instead. I found a topic in the the forum that touches this problem but gives no solution.
    If someone could tell me what i am doing wrong that would be great! Any help would be appreciated. My class is posted below......
    package rateformapplet;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.*;
    public class TreeSections extends JPanel implements TreeSelectionListener
      DefaultMutableTreeNode mainSection = null;
      private JTree jt;
      public TreeSections(Object[][] ro)
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Select The Main Section then Applicable Sub Section(s)");
        createNodes(top,ro); //setup the tree nodes
        //setup Tree values
        jt = new JTree(top);
        jt.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        jt.setSize(300,200);
        jt.setShowsRootHandles(true);
        JScrollPane treeView = new JScrollPane(jt);
        this.add(treeView);
        this.setVisible(true);
        TreeCR cr = new TreeCR();
        jt.setEditable(true);
        jt.setCellRenderer(cr);
      }//end constructor
      //below is a method of the TreeCellRenderClass
      class TreeCR implements TreeCellRenderer
      public Component getTreeCellRendererComponent(JTree tree,Object obj1,
                                                    boolean isSelected, boolean expanded,
                                                    boolean leaf, int row, boolean hasFocus)
        DefaultMutableTreeNode temp = (DefaultMutableTreeNode) obj1;
        //JCheckBox temp2=(JCheckBox)temp.getUserObject();
        JCheckBox x = new JCheckBox(temp.getUserObject().toString());
        return x;
      }//public Component getTreeCellRendererComponent(JTree...........
      private void createNodes(DefaultMutableTreeNode top, Object[][] sections)
        //DefaultMutableTreeNode mainSection = null;
        DefaultMutableTreeNode subSection = null;
        for (int c = 0; c < sections.length; c++)
          mainSection = new DefaultMutableTreeNode(new JCheckBox(sections[c][0].toString()),true);
          top.add(mainSection);
          for (int p = 0; p < sections[c].length; p++)
            subSection = new DefaultMutableTreeNode(new JCheckBox(sections[c][p].toString()),true);
            mainSection.add(subSection);
      }//end create node
    }//end class TreeSectionsThanks in advance
    Chris

    Perhaps this will help somebody.
    When you fill in the nodes (in createNodes), it is not necessary to provide a JCheckBox for each one; just an object whose toString() method will provide the text to the nodes.
    When rendering each cell, set the corresponding text to the JCheckBox.
    I rewrite the TreeCR class and createNode method of the above example, taking this into account:
      class TreeCR implements TreeCellRenderer
        private checkBox = new JCheckBox();
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                      boolean isSelected, boolean expanded,
                                                      boolean leaf, int row, boolean hasFocus)
          DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
          checkBox.setText(node.getUserObject().toString());
          checkBox.setSelected(isSelected);
          return checkBox;
      private void createNodes(DefaultMutableTreeNode top, Object[][] sections)
        DefaultMutableTreeNode mainSection = null;
        DefaultMutableTreeNode subSection = null;
        for (int c = 0; c < sections.length; c++)
          mainSection = new DefaultMutableTreeNode(sections[c][0]);  // without JCheckBox
          top.add(mainSection);
          for (int p = 0; p < sections[c].length; p++)
            subSection = new DefaultMutableTreeNode(sections[c][p]); // without JCheckBox
            mainSection.add(subSection);
      }//end create node

  • JTree selection problem

    I have a problem trying to select a node of a JTree using JDK 1.3.1 and JDK 1.4 beta 3. I use a JTree with a DefaultTreeModel and DefaultMutableTreeNodes.
    Before the tree became visible it has all the nodes loaded but not visible. Then I want to select a path of the tree using a node (DefaultMutableTreeNode) but I not able to do it.
    The path isn't selected and isn't visible.
    I use the following code:
      jTree.setExpandsSelectedPaths(true)
      jTree.setSelectionPath(new TreePath(node.getPath()));
      //I've also tried with
      jTree.expandPath(new TreePath(dmtn.getPath()));Thanks.

    Fair enough. I guess I need to do a bit more reading.
    You have to create a new TreePath object because the
    getPath() method of DefaultMutableTreeNode returns an
    array of TreeNodes where as the setSelected method of
    JTree requires a TreePath object.
    Why are you creating a new path with the contents ofa
    call to getPath?
    wouldn't node.getPath() be what you want toexpend/set
    visible/scroll to etc
    try it without creating a new TreePath

  • JTree leaf selection

    hi guys,
    I am developing a jTree for a networking product,which will show all the network elements present in the network.The tree also shows the device status like Up,Down etc.I have provided a button to refresh the jtree to update the status of the devices.But after updating the jtree when i try to expand or setSelected path to previously selected leaf,the jTree is expanding only till the parent of the leaf.Here is the code which i have written:
    public void addRootNodes()
              TreePath path=jTree.getSelectionPath();
              DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
              TopologyUtilities.getNetworkCollectionDetails();
              TopologyUtilities.getRuntimeDataMapOnRefresh();
              initializeData();
              rootBusiness.removeAllChildren();
              rootNetwork.removeAllChildren();
              rootDiscovery.removeAllChildren();
              addRegionLocationToBusinessView();
              AddNodesToTree.addRoutersToNetworkView(configuredNetworkCollection, dataMap, rootNetwork);
              AddNodesToTree.addRoutersToDiscoveryView(discoveredNetworkCollection, configuredNetworkCollection, dataMap, rootDiscovery);
              treeModel.reload();
              panel.removeAll();
              jTree.setSelectionPath(path);
    Thanks for the help in advance
    bye,
    Srinivas

    Since you have a reference to a DefaultMutableTreeNode object, can't you do something like
    TreeNode[] nodes = n.getPath();
    TreePath path = new TreePath(nodes);
    tree.setSelectionPath(path);

  • JTREE with CheckBox Option

    Hi All,
    Can somebody help in how to add a CheckBox in JTREE node concept.
    Please let me if sites are there for the same.
    Rgds
    Sudhama

    * The CheckedTree is an extension to JTree with the additional functioanlity that
    * the nodes can be checked or unchecked using a checkbox.
    * <p>
    * Each node in the tree contains a checkbox.
    * @author anoopkc
    public class CheckedTree extends JTree {
        private CustomRenderer renderer = null;
        private List<TreePath> selectedNodes = null;
         * Initialises the checked tree
        public CheckedTree() {
            this.selectedNodes = new ArrayList<TreePath>();
            this.setTreeProperties();
         * Sets the properties of the tree
        private void setTreeProperties() {
            this.renderer = new CustomRenderer(this);
            super.setCellRenderer(renderer);
            super.getSelectionModel().setSelectionMode(4);
            super.addMouseListener(new MouseAdapter() {
                 * Handles the click on the tree nodes.
                 * When mouse is clicked on a node, the node is added in the
                 * list of selected rows in the tree.
                 * @param e
                public void mousePressed(MouseEvent e) {
                    TreePath path = getPathForLocation(e.getX(), e.getY());
                    if (path != null) {
                        addSelectedNode(path);
                        updateUI();
         * This method adds the selected path in to the list of selected nodes.
         * If the path is already exists, it is removed from the list.
         * @param path
        private void addSelectedNode(TreePath path) {
            if (selectedNodes.indexOf(path) == -1) {
                selectedNodes.add(path);
            } else {
                selectedNodes.remove(path);
         * This method checks whether a given tree path is selected or not
         * @param path
         * @return true if selected
        public boolean isSelected(TreePath path) {
            if (this.selectedNodes.indexOf(path) == -1) {
                return false;
            return true;
         * Returns the list of selected columns
         * @return list of selected columns
        public List<TreePath> getSeelctedNodes() {
            return selectedNodes;
    * This class creates the renderer for the checked tree
    * @author anoopkc
    class CustomRenderer extends JPanel implements TreeCellRenderer {
        private JLabel label = null;
        private JCheckBox checkBox = null;
        private CheckedTree tree = null;
         * Initialises the renderer
         * @param checkedTree
        public CustomRenderer(CheckedTree checkedTree) {
            this.tree = checkedTree;
            this.prepareComponent();
         * Prepares the component
        private void prepareComponent() {
            creatComponent();
            this.packComponents();
         * Creates the component
        private void creatComponent() {
            this.label = new JLabel();
            this.label.setPreferredSize(new Dimension(100, 21));
            this.label.setForeground(UIManager.getColor("Tree.textForeground"));
            this.label.setOpaque(true);
            this.checkBox = new JCheckBox();
            this.checkBox.setBackground(UIManager.getColor("Tree.textBackground"));
         * Packs the components
        private void packComponents() {
            setLayout(new GridBagLayout());
            setBackground(Color.WHITE);
            GridBagConstraints gbcCheckBox = new GridBagConstraints();
            gbcCheckBox.gridx = 0;
            GridBagConstraints gbcLabel = new GridBagConstraints();
            gbcLabel.gridx = 0;
            gbcLabel.gridx = 1;
            gbcLabel.weightx = 1;
            gbcLabel.fill = GridBagConstraints.HORIZONTAL;
            add(this.checkBox, gbcCheckBox);
            add(this.label, gbcLabel);
         * Returns the tree cell renderer component
         * @param tree
         * @param value
         * @param selected
         * @param expanded
         * @param leaf
         * @param row
         * @param hasFocus
         * @return component
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            TreePath path = tree.getPathForRow(row);
            label.setText(value.toString());
            label.setIcon(new ImageIcon("icons/smiley.gif"));
            if (selected) {
                label.setBackground(new Color(220, 220, 200));
            } else {
                label.setBackground(Color.WHITE);
            if (this.tree.isSelected(path)) {
                this.checkBox.setSelected(true);
            } else {
                checkBox.setSelected(false);
            return this;
    }

  • Help with JTree data by user input

    I am trying to read data into a JTree without it being hardcoded.
    An example of the data is:
    String data[] = {"a","b","c",";","b","g","h",";","c","t",";","g","u"};
    The above data is taken from user input and stored in an array and checked for errors.
    I want to somehow read take the above array's data and put it into following format in some kind of loop but I am not sure how.
    Object[] hierarchy = {"a", new Object[]{"b",new Object[]{"g","u"},"h"},new Object[]{"c","t"}};
    This Object is then passed to a function that interpets it and prints out the appropriate JTREE structure. For the values above it would be:
    a
    ..b
    ....g
    ......l
    ......u
    ....h
    ..c
    ....t
    Tha problem is how to take the string array and put that data correctly into the Object array. I have been racking my feeble mind for quite sometime and if any one out there can see it or has a better idea of how to get my data into the JTree please let me know.
    Thanks

    //OutlookClient.java
    //uses also Console class from Bruce Eckel 
    //<applet code=OutlookClient width=500 height=300>
    //</applet>
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    import javax.swing.UIManager;
    import javax.swing.SwingUtilities;
    import BruceEckel.*;
    import DynamicTree.*;
    import DynamicTreeNode.*;
    import java.lang.reflect.*;
    /* a class creating a dialog with the version, and other details about the program*/
    class AboutDialog extends JDialog {
         private JButton ok = null;
         private Container cp = null;
         private JTextField tname = null;
            public AboutDialog() {
                   //System.out.println("constructor");
                   ok = new JButton("OK");
                   cp = getContentPane();
                   cp.setLayout(new FlowLayout());
                   JLabel tlab = new JLabel("Outlook - client side");
                   cp.add(tlab);
                   //tname.setMinimumSize(new Dimension(50,10));
                   //tname.setSize(new Dimension(70,10));
                   tlab = new JLabel("Author: Jiri Machotka");
                   cp.add(tlab);
                   tlab = new JLabel("version 1.0 (September 2001)");
                   cp.add(tlab);
                   tlab = new JLabel("----------------------------------------------");
                   cp.add(tlab);
                   ok.addActionListener( new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        dispose();
                      }//actionPerformed
                   });//addActionListener
                   cp.add(ok);
                   setSize(200,150);
                   setTitle("About the program");  
                   setModal(true);
         }//constructor
      *      <P>This class more-or-less contains a graphic design object used for interaction with a user.</P>
      *     Apart from all ScrollPanes, Buttons, and MenuItems, it contains also 3 interesting members:
      *     <ol>
      *     <li> <I>protected final DefaultMutableTreeNode topNode</I>, which is initialized with
      * a potent, non-removable object of the class <I>Node</I>
      *     <li> <I>protected final DefaultTreeModel treeModel</I>, which is initialized with the <I>topNode</I>
      *     <li> and finally <I>protected final DynamicTree dyn_tree</I>, which uses the 2 objects above
      *     </ol>
      *     <P> The <I>OutlookClient</I> is an applet, but it can be also processed as an application (thanks to
      *     a library by BruceEckel).</P>
    public class OutlookClient extends JApplet {
    //------------- properties -----------------------------------------
       private Action
            newMail = new AbstractAction ("New Mail", new ImageIcon("images/NewMailIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("NewMail");
         reply     = new AbstractAction ("Reply", new ImageIcon("images/ReplyIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("Reply");
       private JButton
         /*b1 = new JButton("Add a Node"),
         b2 = new JButton("Remove the current Node"),*/ //not used now
         tb1 = new JButton (newMail),
         tb2 = new JButton (reply);
       private JTextField
         txt = new JTextField(10);
       private Container
         leftArea = new Container(),
         rightArea = new Container();
       private JScrollPane
            left = new JScrollPane (leftArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
            right = new JScrollPane (rightArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
       private JSplitPane
            sp = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, left, right);
       private JToolBar
         toolBar = new JToolBar();
       private JMenuBar
         menuBar = new JMenuBar();
       /*ActionListener al = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String name = ( (JButton)e.getSource()).getText();
            txt.setText(name);
       };*/     //not used now - used as an action listener for buttons b1, b2
       private JMenu
         mainOutlookMenu = new JMenu ("Outlook activities"),
         othersMenu      = new JMenu ("Others"),
         mailMenu     = new JMenu ("Mails"),
         chatMenu     = new JMenu ("Chat"),
         look_and_feelMenu = new JMenu ("Look&Feel");
       private JMenuItem
         closeAppItem     = new JMenuItem ("Exit",KeyEvent.VK_F3),
         newMailItem     = new JMenuItem (newMail),
         replyItem     = new JMenuItem (reply);
       private JRadioButtonMenuItem
         windowsLookAndFeelItem;
       protected final DefaultMutableTreeNode topNode = new DefaultMutableTreeNode(new Node ("Outlook", false, true));
       protected final DefaultTreeModel treeModel = new DefaultTreeModel(topNode);
       protected final DynamicTree dyn_tree = new DynamicTree(topNode, treeModel);
    //-------------inner classes----------------------------------------
    /** <P>The class <I>MyRenderer</I> sets the renderer of the tree - by doing that icons can be assigned to
       * the tree's nodes. </P>
       * <P> It sould be probably a standard member of a class <I>DynamicTreeWithIcons</I>.</P>
       * <P> However, it uses the knowledge that the class <B>Node</B>, which is the only object that can be
       * found in the dynamic tree in this application, has a method <I>getIcon()</I>, which returns a
       * reference to the icon object assigned to the node.</P>
       * <P><B>This is the only place, where the class Node, or its methods are called explicitely.</B></P>
       protected class MyRenderer extends DefaultTreeCellRenderer {
         /** The constructor of the class.
           * - sets folders icons (opened, closed folder)
         public MyRenderer() {
                 //setLeafIcon(new ImageIcon("images/middle.gif")); //for leaves' icon, all at once!
              setOpenIcon(new ImageIcon("images/folder_open.gif"));
              setClosedIcon(new ImageIcon("images/folder_close.gif"));
         /** This overridden method gets the user-specified icon for leaf nodes. */
         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 (leaf) 
              //workaround: test if icon not eq. null
                     ImageIcon ic = getRightIcon(value);
                     if (ic == null) return this;
                     else
                          setIcon(ic);
              return this;
         }//overridden: getTreeCellRendererComponent
         private ImageIcon getRightIcon(Object value) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              try{
              Node node_object = (Node)(node.getUserObject());   
                 return (node_object.getIcon());
           catch (Exception e) { return null; }
         }// ImageIcon getRightIcon(Object value)
      }//class MyRenderer
    //-------------OutlookClient methods-----------------------------------------
       private void assignListeners(){
         dyn_tree.addTreeSelectionListener(new TreeSelectionListener() {
             public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)dyn_tree.getLastSelectedPathComponent();
              if (node == null) return;
              if (node.isLeaf()) { txt.setText(node.toString()); }
       }//assignListeners()
       private void createLayout(){
         leftArea.setLayout(new BoxLayout(leftArea,BoxLayout.Y_AXIS));
         rightArea.setLayout(new BoxLayout(rightArea,BoxLayout.Y_AXIS));
         //left.setMinimumSize(new Dimension(120,200));
         right.setMinimumSize(new Dimension(50,50));
         //rightArea.add(b1);
         //rightArea.add(b2);
         rightArea.add(txt);
         //leftArea.add(tree);  ... not nice (why?)
           left = new JScrollPane (dyn_tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);       
         left.setMinimumSize(new Dimension(180,200));
         sp.setLeftComponent(left);
       }//createLayout()
       private void createMenu(){
         ButtonGroup group = new ButtonGroup();
            JRadioButtonMenuItem rbMenuItem;
         closeAppItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, ActionEvent.ALT_MASK));
         closeAppItem.getAccessibleContext().setAccessibleDescription("Closes application");
         closeAppItem.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {System.exit(0);}
         othersMenu.setMnemonic(KeyEvent.VK_O);
         othersMenu.getAccessibleContext().setAccessibleDescription("System settings&Others");
            rbMenuItem = new JRadioButtonMenuItem("Java");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_J);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF(UIManager.getCrossPlatformLookAndFeelClassName( ) );}
            look_and_feelMenu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Windows");
            rbMenuItem.setMnemonic(KeyEvent.VK_W);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");}
            look_and_feelMenu.add(rbMenuItem);
         windowsLookAndFeelItem = rbMenuItem;
         look_and_feelMenu.setMnemonic(KeyEvent.VK_L);
         look_and_feelMenu.getAccessibleContext().setAccessibleDescription("Look&Feel");
         JMenuItem aboutItem = new JMenuItem ("About");
         aboutItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   AboutDialog ad = new AboutDialog();
                   ad.show();
         othersMenu.add(look_and_feelMenu);
         othersMenu.addSeparator();
         othersMenu.add(aboutItem);
         othersMenu.addSeparator();
         othersMenu.add(closeAppItem);
         mainOutlookMenu.setMnemonic(KeyEvent.VK_A);
         mainOutlookMenu.getAccessibleContext().setAccessibleDescription("Outlook activities");
         menuBar.add(mainOutlookMenu);
         menuBar.add(othersMenu);
         mailMenu.setMnemonic(KeyEvent.VK_M);
         mailMenu.getAccessibleContext().setAccessibleDescription("Mail activities");
         chatMenu.setMnemonic(KeyEvent.VK_C);
         chatMenu.getAccessibleContext().setAccessibleDescription("Chat");
         chatMenu.setEnabled(false);
         mainOutlookMenu.add(mailMenu);
         mainOutlookMenu.addSeparator();
         mainOutlookMenu.add(chatMenu);
         //mailMenu.add(newMail);
         //mailMenu.add(reply);     //class Action has problems to catch the accelerator keys
         newMailItem.setMnemonic(KeyEvent.VK_N);
         replyItem.setMnemonic(KeyEvent.VK_R);
         mailMenu.add(newMailItem);
         mailMenu.add(replyItem);
         newMailItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
         replyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
         //newMail.putValue(Action.NAME, "New mail");
         //newMail.putValue(Action.SHORT_DESCRIPTION, "New mail");
         //newMail.putValue(Action.LONG_DESCRIPTION, "New mail");
         //newMail.putValue(Action.MNEMONIC_KEY, "N");  //cast an exception. why?
         //newMail.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));     
         setJMenuBar(menuBar);
       }//createMenu()
       private void createToolBar(){
         //toolBar.add(newMail);
         //toolBar.add(reply);    //does not provide texts and mnemonics
         tb1.setMnemonic(KeyEvent.VK_N);
         tb2.setMnemonic(KeyEvent.VK_R);
         toolBar.add(tb1);
         toolBar.add(tb2);
       }//createToolBar()
       private void createNodes(DefaultMutableTreeNode topNode){
         //new for dynamic processing
         DefaultMutableTreeNode
              parentNode = null,
              leaveNode  = null;
         parentNode = dyn_tree.addObject(null,new Node ("MailFolders", false, true));
         dyn_tree.addObject(parentNode,new Node ("Inbox","images/InboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Outbox","images/OutboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Sent","images/SentIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Deleted","images/DeletedIcon.gif", false, false));
         //leaveNode.setEnabled(false);  //TODO: disable "Chat"node
         dyn_tree.addObject(null,new Node ("Chat", false, false));
       }//createcreateNodes(DefaultMutableTreeNode)
       private void setTreeSettings(){
         //one selection at one time
         dyn_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         //connect nodes with a thin line - Java style only
         dyn_tree.putClientProperty("JTree.lineStyle","Angled");
         //collapse the root's children first
         //tree.setShowsRootHandles(false);
         //icon adjustment
         MyRenderer MyRen = new MyRenderer();
         dyn_tree.setCellRenderer(MyRen);
         //modifiable tree - by double click - allows modifying of nodes' names
         // but unfortunately also restores original icons
         //tree.setEditable(true);
       }//setTreeSettings()
       private boolean setPLAF(String LookAndFeelName){
          try{
         UIManager.setLookAndFeel(LookAndFeelName);
         SwingUtilities.updateComponentTreeUI(this);
         return true;
          } catch (Exception e) {
         //e.printStackTrace(System.err);
         return false;
       }//setPLAF(String LookAndFeelName)
       private void trytosetLookAndFeel(){
          if (setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))
              windowsLookAndFeelItem.setSelected(true);
       }//trytosetLookAndFeel()
       /** The applet's <I>init()</I>.
         * Calls methods to construct all visible objects.
         * Apart from that it also assigns the renderer to the tree.
       public void init(){
         sp.setOneTouchExpandable(true);
            //sp.setDividerLocation(150); - system puts the value to optimize the left part
         sp.setPreferredSize(new Dimension(450,200));
         Container cp = getContentPane();
         cp.setLayout(new FlowLayout());
            createLayout();     
         createMenu();
         createToolBar();
         createNodes(topNode);
         setTreeSettings();
         //createPopupMenu();
         assignListeners();
         cp.add(toolBar);
         cp.add(sp);
         trytosetLookAndFeel();
       }//init()
       /** If called as an application.
         * The desired Windows Look&Feel is re-set again, when the applet is running. Otherwise, it in an application
         * it tends not to work correctly.
       public static void main(String[] args) {
         OutlookClient theApplet;
         BruceEckel.Console.run(theApplet=new OutlookClient(), 500, 300);
         theApplet.trytosetLookAndFeel();
       }//main(String[])
    }///:~Take a look namely at createNodes
    Hope it helps.

Maybe you are looking for