Help with JTree

I wrote a cls that extends JTree....I have defined the root node in this class.
Public class a extends JTree{
/// global variable nd constructor
public void JTReader()
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
           m_model = new DefaultTreeModel(root);
            //program logic to get the parent and child nodes
       //method defined for adding child to parent
       addNode (child,parent);
      //rest of the code
     expandRoot();
     setBounds(0,0,500,500);
public void addNodeTo(String childNodeName, String parentNodeName)
          //code for chking if the node is already present
          //add child to parent at the end of child list
          ((DefaultTreeModel)getModel()).insertNodeInto(childNode, parentNode, parentNode.getChildCount());     
     }     I want to call this class in my main program which extends Jpanel�.
I have written this
public class LibGui extends JDialog{
private JTreeReader tree;
  JTree newtree;
Constructor{
    libInit();
void libInit() throws Exception {
initializing the panel�
         updateclslist(projectName);
        libScrollPane = new JScrollPane(tree);
        libScrollPane.add(tree);
       clslistHolder.add(libScrollPane, BorderLayout.CENTER);
      cbPanel.add(clslistHolder, BorderLayout.CENTER);
//rest of code
protected void updateclslist(String projectName){
    JTreeReader tr = new JTreeReader(projectName);
    tree.JTReader();
     }       

Swing related questions should be posted in the Swing forum.
The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]How to Use Trees has working examples.

Similar Messages

  • Help with JTree Update

    Hi there,
    I need to do a simple thing with a JTree but I 've got a problem. Well I want to create a very very very simple bookmark function. I have a tree with the children and I want to add new children which are going to work like link for my program. I try to add new children the same way I created them but it's not working. I tried also the updateUI method that somebody mentioned in an other topic but still nothing. Can somebody help?
    Here is the Bookmark Panel code:
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.awt.*;
    public class BookmarkTry implements TreeSelectionListener {
        private JScrollPane scrollPane;
        private JLabel label;
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Bookmarks");
        private JTree tree;
        private JPanel panel = new JPanel();
         public BookmarkTry(){
         public JPanel createpanel(){
         tree = new JTree(root);
         root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 1","about.html")));
        root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 2","aaa.html")));
        root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 3","sdss.html")));
        // build tree
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.addTreeSelectionListener(this);// get selection events!
        // build form
        scrollPane = new JScrollPane(tree);
        label = new JLabel(" ");
        //scrollPane.setViewportView(tree);
        panel.add(label);
        panel.add(scrollPane);
        return panel;
        public void addBookMarks(String name, String page){
             root.add(new DefaultMutableTreeNode(new Bookmark(name,page)));
             //DefaultTreeModel.reload();
        public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if ((selectedNode!=null)&&(selectedNode.isLeaf())) {
                Bookmark b = (Bookmark)selectedNode.getUserObject();
                label.setText("Go to page "+b.getPage());
        private static class Bookmark {
            private String caption;
            private String page;
            public String getPage() {
                return page;
            public Bookmark(String caption, String page) {
                this.caption = caption;
                this.page = page;
            public String toString() {
                return caption;
         and here how I try to add the node :
    void jButton1_actionPerformed(ActionEvent e) throws java.sql.SQLException {
            DefaultMutableTreeNode book = null;
            System.out.println("You pressed the add button of bookmarkframe");
            //Bookmark.getTreePanel().addObject(name.getText());
            //book = new DefaultMutableTreeNode(new BookInfo(name.getText(),page.getText()));
            System.out.println(name.getText());
            System.out.println(page.getText());
            tempb.addBookMarks(name.getText(),page.getText());
            frame.dispose();
       } //void jButton1_actionPerformedIt doesn't add the new node in my JTree
    Thanks in advance

    I still suspect you have two (or more) new BookmarkTry() executions somewhere. But I can't see all of your code here of course. My standard reply, so we don't waste time guessing:
    1) In the future, Swing related questions should be posted in the Swing forum.
    2) If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    Note, we don't want your whole application. We want an SSCCE!

  • Help with JTree and JList

    Hi everybody!
    My problem is this:
    I have in a panel a JTree. This tree has a root and several children called GROUPs. Every GROUP has several children called MODULEs. Every MODULE have several children called RULEs.
    The JTree is already constructed with a function that I have implemented and that reads the data necessary to fill the tree.
    What I would like to get, and I do not know how, is that when I press with the mouse in "Root" I can see a list, on the right side of the tree, with all the GROUPs that it contains. Besides, when I press with the mouse in a GROUP I can see the list of MODULEs that it contains. And finally that when I press with the mouse in a MODULE I can see the RULEs that it contains.
    I think that it is done by using listeners and so on, but actually I do not understand well how it works.
    I would be very grateful whether any of you could show me a piece of code (at least some guidelines) of the function that I would have to implement. And of course, a little bit of explanation about the use of listeners and so on that are necessary to do these kind of things.
    I am a total begginer and I need your help.
    Thanks a lot in advance,
    Fran.

    Please, helpppppppppppp!!!!!!!!!!!!!!!!!!!!!!!
    :)

  • Please help with JTree.setSelectionPath

    Hi....i have a split window, with a JTree on the left and a heap of small pic on the right. If i select any node in the tree, my program can highlight the corresponding pic on the right. Now, my problem is how to select the tree node, if i select the pic on the right first.
    I tried to use setSelectionPath(TreePath)...but i couldnt get the TreePath. I also tried to create a new path, by
    TreePath path1 = new TreePath(Object[]{root, object1});
    where, object1 is the selected object from the right split (the pic)
    Please help me...thanx a lot !!

    Please go to
    http://forums.java.sun.com/thread.jsp?forum=57&thread=164386
    Hope this will help u

  • Pls help with JTree editor problem

    Hi,
    I have a JTree where each node in the tree is a JPanel. In each
    JPanel are two JTextField objects. Only one of the JTextField objects
    is editable.
    When I click on node (a line in the JTree) with the mouse, it is
    painted using the custom editor (TreeCellEditor) that I have written.
    When the selected and editable JTextField has the focus, and when a
    certain key is hit, I capture that key, do some things, and then select
    a different node in the JTree.
    When selecting the new node, I need the node to be painted with
    the editor, just as if I had clicked on it with the mouse.
    In the method called as a result of the key binding, I call the
    following --
    TreeUI.stopEditing( JTree ) -- stops editing of the cell that resulted
    in the key binding call
    TreeUI.startEditingAtPath( JTree, TreePath )
    -- according to the JavaDocs, this should select the new cell and
    start editting of it.
    This last method does call my editor to get the components, but then my
    Renderer is also called (twice in fact). When the cell is painted, it is
    painted with the Renderer's components.
    PLEASE HELP HERE !

    Thank you so much for giving a reply to this problem.
    I will experiment with your suggestion. However, in looking at the JavaDocs
    I would need to make one class that implements both TreeCellEditor and
    TreeCellRenderer, with the methods getTreeCellEditorComponent() and getTreeCellRendererComponent(). Since currently, my editor is called and then
    my renderer is called, over-writing the editor's result, I would suspect that
    both of these methods would also be called (even though they are in the same
    class), having the same effect.
    Again, thank you.

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

  • Help with JTree node handles icon

    Hi
    In my application i use Jtree to display the hirearchical data.But i don't want to the node handles icon to be displayed in the screen.The root node handle icon will be not be displayed if we set jtree.setShowsRootHandles(false) .Is there any way to diable the other node handles icons too?.Please help me in overcoming the problem.
    So, i will be handling the expand/collapse operations of the node with the help of mouse click event.
    Thanks in advance.
    Regards,
    Krish.

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

  • Help with JTree's opaque methods

    I have been looking through the methods provided for JTree in Netbeans GUIBuilder and I do not see accessor methods for actions like insertion, retrieval, deletion and replacement. I am looking for something like this.
    JTree.insert('object', JTree.getSelectedNode());
    JTree.getSelectedNode().getObject();
    JTree.deleteNode(JTree.getSelected());
    JTree. supplantObject(‘object’, JTree.getSelectedNode());
    JTree.insert('object', JTree.getSelectedNode()) should accept to inputs; the object you wish to insert and the location you wish to insert it. JTree.getSelectedNode() would be an accessor method returning the selected node. The insert would have to find the next available element in the LinkedList, array, hashtable, stack, (or whatever it uses) and inserts the object.
    JTree.getSelectedNode().getObject(); I assume that if I have “apple” selected in the JTree, “apple” will be returned.
    JTree.deleteNode(JTree.getSelected()); deleting the node wipes out all its children as well.
    JTree. supplantObject(‘object’, JTree.getSelectedNode()); overwrites the object in the selected with a new object.
    These seem like the more obvious accessor methods and I am astonished to find them missing or named something inconsistent with java standards.
    So I guess my question is, what are the equivalent method names for the aforementioned methods?
    BM

    Take a look at [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html] which has most of the methods that you are interested in. A JTree has a single root node, which by default is of this type.

  • Help with JTree refresh

    I am having trouble displaying a JTree with newly added nodes.
    I have a JTree, inside a JPanel, JScrollPane and JSplitPane.
    I create the JTree with a single root node which displays correctly.
    I update the JTree with new children which displays correctly.
    Using the same exact routine as above - I add additional new children to the root, the new children do not display in the JTree.
    I have confirmed that I am using the correct tree and root node in debug that the tree/node objects has been correctly updated. It is just not displaying the new children to the root.
    I can expand and collapse the tree which does not show the new children, just the original populated root.
    After the root has been updated, I have tried a number of methods to resolve: tree/jpanel/jscrollpane/jsplitpane .revalidate, invalidate, repaint, etc.
    I am using v1.4.1.
    What am I missing here?
    Thanks in advance.

    i use two classes fro add or insert nodes in a tree, one adds the node at the same level of the current selected node, and the other intert it inside:
    // InsertaTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class InsertaTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public InsertaTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public InsertaTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              //insertIndex = parent.getIndex(insertNode) + 1;
              //insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo Insertado"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);
    // AnadeTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class AnadeTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public AnadeTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public AnadeTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              insertIndex = parent.getIndex(insertNode) + 1;
              insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo A�adido"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);

  • Help with JTrees

    Hello,
    I have a JTree and I need it's items to display as stylized text. Or in other words, I want the listed leafs on the JTree to sometimes be bold, colored, underlined, superscript, etc. The style of each JTree leaf will be determined by the properties of a SimpleAttributeSet.
    Basically, is there a way to turn the cells that render each node into DefaultStyledDocuments so that I can call insertString( int offs, String str, AttributeSet a) on it?
    Thanks a lot for any help on this,
    - kevin

    Btw, The other arguments in the method (selected, expanded, leaf, row and hasFocus) allow you to further customize a rendered node.
    ie. if a tree's row is selected, the selected flag will be true, you should have something like:
    if(selected)
      // render it as 'selected', ie change the background color or something
    }in your getTreeCellRendererComponent() method.
    The "row" integer tells you what row in the tree you are at, so you can also customize things further using that argument.

  • Need HELP with JTree created by user input

    I have been trying to create code that takes a user input string
    ex: a:b,c;b:g,h,j;g:k,m;b:u
    note: (the above string is then stored into a string array such in the format a:bc;b:ghj;g:km;b:u after it is verified that the hierarchy order is correct)
    The string is read in such that the any value before the : is a parent and its childern continue until a ; is found. Anyway verifying the sting I have accomplished and I have been able to input the string into a modified binary tree as long as there are only 2 childern per parent and graphically represents its structure of hierarchy. The problem is that each parent can have more the two childern.
    I have been working with the BTree class and find its output similar to what I am wanting which would represent a hierarchy of objects (files, employees, etc...) anyway I have been stumped as to how to get the above string into a format that can then create the correct JTree output without hard code.
    If any one has any suggestions on how to turn the data, in the string array into a usable format to create the correct JTree output, I would greatly appreciate it.
    In the above example the string array, a:bc;b:ghj;g:km;b:u would have a desired ouput of
    a
    ..b
    ....g
    ......k
    ......m
    ....h
    ....j
    ....u
    ..c
    Thanks
    Shane

    I have been trying to create code that takes a user input string
    ex: a:b,c;b:g,h,j;g:k,m;b:u
    note: (the above string is then stored into a string array such in the format a:bc;b:ghj;g:km;b:u after it is verified that the hierarchy order is correct)
    The string is read in such that the any value before the : is a parent and its childern continue until a ; is found. Anyway verifying the sting I have accomplished and I have been able to input the string into a modified binary tree as long as there are only 2 childern per parent and graphically represents its structure of hierarchy. The problem is that each parent can have more the two childern.
    I have been working with the BTree class and find its output similar to what I am wanting which would represent a hierarchy of objects (files, employees, etc...) anyway I have been stumped as to how to get the above string into a format that can then create the correct JTree output without hard code.
    If any one has any suggestions on how to turn the data, in the string array into a usable format to create the correct JTree output, I would greatly appreciate it.
    In the above example the string array, a:bc;b:ghj;g:km;b:u would have a desired ouput of
    a
    ..b
    ....g
    ......k
    ......m
    ....h
    ....j
    ....u
    ..c
    Thanks
    Shane

  • Help with JTree and JPanel (or JFrame)

    Hi! I've an application that has JLabel, JTextField, JTree and JScrollPane.
    The problem is that when I add the tree to the scrollpane and then add it to the frame (or panel), the tree is not displayed. The labels and textfields are there, but the tree is not. But, if I don't use the scroll, just add the tree, then the tree is visible.
    Why is this happening?
    Hope u can help me!

    Please, helpppppppppppp!!!!!!!!!!!!!!!!!!!!!!!
    :)

  • Help with Jtree for a file navigator

    Hi there,
    I'm trying to do something with a JTree, but I can't find anywhere how to perform that.
    I'm making a little file explorer, with a JTree to navigate through the file structure. I have also two buttons (up and back). When I select a directory with the mouse, the corresponding node is highlighted, but when I push the button up, or the button back, it isn't (I mean, the directory is caught well, but no nodes are highlighted). It uses the DefaultTreeCellRenderer
    Any ideas to highlight the directory when I push the up or back button?.
    Thank you very much!!!!

    Strange. Does this small, simplified example work for you?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Xxx extends JFrame implements ActionListener {
      private JTree tree = new JTree();
      private JButton butt = new JButton("!");
      public static void main(String[] args) {
        new Xxx();
      public Xxx() {
        getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
        getContentPane().add(butt, BorderLayout.SOUTH);
        butt.addActionListener(this);
        pack();
        setVisible(true);
      public void actionPerformed(ActionEvent e) {
        int[] rows = tree.getSelectionRows();
        if ((rows != null) && (rows.length == 1)) {
          int next = rows[0] + 1;
          if (next >= tree.getRowCount()) {
            next = 0;
          tree.setSelectionRow(next);
    }

  • Need help with JTree

    I am presently developing an application in which i will like to use JTree to display the directories and files i have on my hard drive. such that when i click on a file, under the JTree it displays the full path in a text field.
    Thanks in advance.

    Try "displaying directories" in the forum search; I got tons of hits.
    DB

  • Please help with JTree Node Duplication

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

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

Maybe you are looking for

  • IPod Pref Pane in iTune 7.0.1 Does Not Work - Do I have too many playlists?

    I'd love to be able to submit a screen shot of this. When I connect my iPod (4G, 3G and Nano), the iPod Preference Pane pops up. I have 50,000 songs in my iTunes library and about 3,000 playlists so I always use the "selected playlists" option. What

  • Display blanks and reappears

    I have a MAC mini and have a Princeton 19" monitor using the DVI connector. I loaded Tiger about a month ago, but have noticed that recently the display has been blanking. The display totally goes black for a couple of seconds and then comes back. I'

  • Creating Table in Email Content

    Hi All, My requirement is to send report output as email content (Not as Attachment). And all the row and column border shoud be visble. Thanks

  • I want to know last Invoice Which i added through Business Object

    Hi All, I want to know last invoice details which i added by Business Object. Can you give the solution???????. Please consider the multi-user environment and Document Series also. Thanks in Advance Regards, G.Suresh

  • Hostid change on reboot causes zpool failure to load

    Seems every time I restart my Solaris 11 Express PVM the hostid is regenerated thus causing a failure for zfs to load pool 'tank' zfs: [ID 427000 kern.warning] WARNING: pool 'tank' could not be loaded as it was last accessed by another system (host: