JTree update

Hey,
in one of the tools I am currently writing I am displaying data in a JTree.
The user can edit the data that goes with the nodes,save the tree (not yet) and load a tree from a local file.
Right now I want the user to be able to "reset" the tree. That means, whenever the user goes to "File - New Tree" he/she should get a new empty JTree.
I put the JTree into a JScrollpane, which is part of a SplitPane, which is part of a JPanel, which is part of a JFrame.
I wrote a little method "resetTree()" to update the tree.
In this method I tried to just call the setup method again - which build the tree in the first place - but I was still able to see the old tree in my GUI.
I tried to repaint all of the Panes above but that did not work either.
//My constructor:
public MyProgram() extends JPanel
JFrame frame = new JFrame("Test");
setupTree();
setupSplitpane(); //This just takes the two ScrollPanes (one for each side) and
//sets up a SplitPane
this.setLayout(new BorderLayout());
this.add(splitPane,BorderLayout.CENTER);
frame.getContentPane().add(this,BorderLayout.CENTER);
frame.pack();
//This is the method which I call when creating the tree for the first time.
private static void setupTree(String from)
//TreeBuilder builds the tree. It can read a local xml file into
//the tree. "from" is the path of the file. "data" is a Hashtable.
//The method puts the data from the xml file into "data" and builds a tree.
TreeBuilder myTreeBuilder = new TreeBuilder(from,data);
//"tree" is a global JTree. "getTree()" returns the JTree myTreeBuilder build.
tree = myTreeBuilder.getTree();
//treeView is the JScrollPane
treeView = new JScrollPane(tree);
treeView.setPreferredSize(new Dimension( leftWidth, windowHeight ));
tree.addMouseListener(new PopupListener(popup));
//This is the method I call when trying to reset the tree.
public void resetTree(String from)
data = null;
setupTree(from); //from = null in this case.
splitPane.repaint(); //Repaint the Splitpane
frame.repaint(); //Repaint the Frame
this.repaint(); // Repaint the Panel.
Again, my problem is, that when I call resetTree() the tree I can see in my GUI does not change. I want the tree in the left side of my JSplitpane to be setup again from zero (containing no data and no nodes) and than to update the GUI.
I hope somebody got what I am trying to do and is able to show me a solution or just give me a little hint on howto solve this problem.
THX!
Martin

Thank you very much!
I got it working like this:
JTree tree = myX.getTree();
DefaultTreeModel mdel = (DefaultTreeModel)(tree.getModel());
Object t = mdel.getRoot();
if(t instanceof DefaultMutableTreeNode)
DefaultMutableTreeNode root = (DefaultMutableTreeNode)(t);
root.removeAllChildren();          
mdel.reload();
Still quick and dirty but it works...
THX
Martin

Similar Messages

  • I HATE JTREE UPDATES!!!

    I've tried everything I can think of, but the JTree never updates properly.
    Here's an example of what's going on.
    I have a JTree that uses Drag and Drop. I have 2 folders in the C:\ drive. They are C:\NewFolder1 and C:\NewFolder2
    I open Windows Explorer and drag C:\NewFolder1 into my JTree, dropping it in C:\NewFolder2
    Windows Explorer shows it now as C:\NewFolder2\NewFolder1, however my bastard JTree never changed. When I try to refresh the JTree, I can get the JTree to collapse itself, but when I re-expand it, it is the same old structure.
    Below is the relevant portions of code... Any suggestions?
        // ------------------TREE CREATION--------  //
        DFM = new DefaultTreeModel( getRoot() ); //The Default Tree Model
        tree = new JTree( DFM );
        tree.setToggleClickCount(1);
        tree.setCellRenderer( new MyTreeRenderer() );
        tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); //set single selection for the Tree
        tree.addTreeSelectionListener( new TreeSelectionListener()
          public void valueChanged( TreeSelectionEvent e )
            DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) tree.getLastSelectedPathComponent();
            getChildren( node );
        scrollPane1.getViewport().add( tree, null );
    // Should properly rebuild JTree //
      public void refreshTree()
        DFM.reload( getRoot() );     //getRoot() returns a DefaultMutableTreeNode
        //tree.setModel(DFM);
        //tree = new JTree(DFM);
        //scrollPane1.removeAll();
        //scrollPane1.getViewport().add( tree, null );
        scrollPane1.revalidate();
        scrollPane1.repaint();
      }

    Below is my code...Maybe someone can spot something out of the ordinary?
    package DND;
    import jExplorer.DiskObject;
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.StringSelection;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.*;
    import java.io.File;
    public class AutoscrollTree extends JTree implements Autoscroll, DragGestureListener, DragSourceListener
      private static final int AUTOSCROLL_MARGIN = 25;
      private Insets autoscrollInsets = new Insets( 0,0,0,0 );    // AutoScroll methods.
      private DefaultTreeModel dtModel;
      private DefaultMutableTreeNode root;
      public AutoscrollTree( DefaultMutableTreeNode root )
        super();
        this.root = root;
        dtModel = new DefaultTreeModel( root );
        setModel( dtModel );
        DragSource dragSource = DragSource.getDefaultDragSource();
        dragSource.createDefaultDragGestureRecognizer(
          this, // component where drag originates
          DnDConstants.ACTION_COPY_OR_MOVE, // actions
          this ); // drag gesture recognizer
        new DropTarget( this, getTargetListener() );
    // AUTO SCROLLING //
      public void autoscroll( Point location )
      {        //System.out.println("mouse at " + location);
        int top = 0, left = 0, bottom = 0, right = 0;
        Dimension size = getSize();
        Rectangle rect = getVisibleRect();
        int bottomEdge = rect.y + rect.height;
        int rightEdge = rect.x + rect.width;
        if( location.y - rect.y <= AUTOSCROLL_MARGIN && rect.y > 0 ) top = AUTOSCROLL_MARGIN;
        if( location.x - rect.x <= AUTOSCROLL_MARGIN && rect.x > 0 ) left = AUTOSCROLL_MARGIN;
        if( bottomEdge - location.y <= AUTOSCROLL_MARGIN && bottomEdge < size.height ) bottom = AUTOSCROLL_MARGIN;
        if( rightEdge - location.x <= AUTOSCROLL_MARGIN && rightEdge < size.width ) right = AUTOSCROLL_MARGIN;
        rect.x += right - left;
        rect.y += bottom - top;
        scrollRectToVisible( rect );
      public Insets getAutoscrollInsets()
        Dimension size = getSize();
        Rectangle rect = getVisibleRect();
        autoscrollInsets.top = rect.y + AUTOSCROLL_MARGIN;
        autoscrollInsets.left = rect.x + AUTOSCROLL_MARGIN;
        autoscrollInsets.bottom = size.height - ( rect.y + rect.height ) + AUTOSCROLL_MARGIN;
        autoscrollInsets.right = size.width - ( rect.x + rect.width ) + AUTOSCROLL_MARGIN;
        return autoscrollInsets;
    // Drag Listeners                                               //
      public void dragGestureRecognized( DragGestureEvent e )
        // drag anything ...
        String directory = getDirectory();
        e.startDrag( DragSource.DefaultCopyDrop, // cursor type
          new StringSelection( directory ),      // transferable
          this );                                // drag source listener
        System.out.println( "Start: " + directory );
      public void dragDropEnd( DragSourceDropEvent e )
        String directory = getDirectory();
        System.out.println( "End: " + directory );
      public void dragEnter( DragSourceDragEvent e )
        System.out.println( "Enter" );
      public void dragExit( DragSourceEvent e )
        System.out.println( "Exit" );
      public void dragOver( DragSourceDragEvent e )
        //  System.out.println( "Over" );
      public void dropActionChanged( DragSourceDragEvent e )
        System.out.println( "Action Changed" );
    // DROP LISTENERS //
      public DropTargetListener getTargetListener()
        DropTargetListener dtl = new DropTargetAdapter()
          public void dragOver( DropTargetDragEvent dtde )
            int x = dtde.getLocation().x;
            int y = dtde.getLocation().y;
            TreePath path = getClosestPathForLocation( x, y );
            if( path != null )
              setSelectionPath( path );
          public void drop( DropTargetDropEvent dtde )
            try
    // Ok, get the dropped object and try to figure out what it is.
              Transferable tr = dtde.getTransferable();
              DataFlavor[] flavors = tr.getTransferDataFlavors();
              for( int i = 0; i < flavors.length; i++ )
                System.out.println( "Possible flavor: " + flavors.getMimeType() );
    // Check for file lists specifically.
    if( flavors[i].isFlavorJavaFileListType() )
    // Great! Accept copy drops...
    dtde.acceptDrop( DnDConstants.ACTION_COPY );
    System.out.println( "Successful file list drop.\n\n" );
    // And add the list of file names to our text area
    java.util.List list =
    ( java.util.List ) tr.getTransferData( flavors[i] );
    // Destination directory
    String directory = getDirectory();
    File dir = new File( directory );
    for( int j = 0; j < list.size(); j++ )
    // Source File
    File file = (File)list.get(j);
    // Move file to new directory
    boolean success = file.renameTo(new File(dir, file.getName()));
    if (success)
    System.out.println( "Moved "+list.get(j) + " to "+directory+"\n" );
    else
    System.out.println( "<ERROR>: Could not move "+list.get(j)+" to "+directory );
    // If we made it this far, everything worked.
    dtde.dropComplete( true );
    // rebuild jtree
    //if source folder still exists
    // expand tree at source folder
    // else expand tree at parent folder
    // refresh table to match jtree
    //refreshTree();
    return;
    // Hmm, the user must not have dropped a file list.
    System.out.println( "Drop failed: " + dtde );
    dtde.rejectDrop();
    catch( Exception e )
    e.printStackTrace();
    dtde.rejectDrop();
    return dtl;
    // MISC FUNCTIONS //
    public String getDirectory()
    TreePath tp = getSelectionPath();
    if( tp != null )
    DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) tp.getLastPathComponent();
    DiskObject dObj = ( DiskObject ) dmtn.getUserObject();
    return dObj.getPath();
    return null;
    public void refreshTree()
    System.out.println( "Refreshing Tree" );
    dtModel.reload( root );
    //dtModel.nodeChanged( root );
    //dtModel.nodeStructureChanged( root() );
    //setModel(dtModel);
    //new AutoscrollTree(dtModel);

  • Preventing JTree updates from uncompleted JTable edits

    Hello there!!
    I have an applet that displays an xml file in a JTree. Each node of the table represents specific elements of the xml file (some are not displayed by design). Also on the applet is a JTable that updates the displayed information depending on what node of the tree is clicked. The information displayed in the table includes names and values of attributes and names and values of xml elements not displayed in the JTree.
    I can edit values in the table and update that tree effectively, so that is not a problem.
    The problem I have is that if the user enters a value in the table, does not press enter and then clicks on another tree node, the entered value is copied into the new tree node. I would like to ignore all values if the user does not specifically press enter.
    I have seen some code examples in previous posts that partially work, but can't get the entered values to be totally ignored.
    I'm currently using the following code to handle the 'didn't press enter' bug.
            table.getEditorComponent().addFocusListener(
                    new java.awt.event.FocusListener(){
                public void focusGained(java.awt.event.FocusEvent e) {}
                public void focusLost(java.awt.event.FocusEvent e){
                    if ( table.getEditingRow() > -1 &&
                            table.getEditingColumn() > -1 ){
                        ((javax.swing.DefaultCellEditor)table.getCellEditor()).stopCellEditing();
            });So my question is: How do I prevent the value entered in the table cell from being copied to the newly clicked on tree node? Any assistance would be great.
    Thanks (even just for reading!)
    Simon
    PS. When are we going to see the back of the stupid censorship in this forum?

    Not too sure if this will help but here goes...
    Normally in a JTable, editing is automatically stopped when the enter key is pressed so there is no need to do anything special there. If you don't want editing to stop when the mouse is clicked elsewhere in the table, what you should do is call cancelEditing() instead of stopEditing() in your focusLost method.
    ;o)
    V.V.

  • JTree Update Leaf Icon

    Hi,
    I have two problem with Jtree.
    1.How can I put different Icons for different leafs of the same node?
    2.How is it possible to refresh or update the Jtree(by adding or removing some leaf) that the leaf Icons remain?
    Thanks for your help.

    1.How can I put different Icons for different leafs of the same node?Yes, ... either write a custom cell renderer or find a "merged icon".. there are examples of both around the forums.
    2.How is it possible to refresh or update the Jtree(by adding or removing
    some leaf) that the leaf Icons remain?No. if you remove a node, the node is gone. If you don't remove the node, the node stays. IF you want to leave the leaf icon, you can have a renderer which just displays the icon and not the text.

  • JTree: Updating a single node

    I have a Jtree and need, during the course of the apps execution, update the information in the tree, specifically change the icons of individual nodes. setLeafIcon() allows you to change the icon for the entire model, but I just need to change it for individual nodes. anyone else implement this or have any ideas?
    thanks.
    -karl

    ok, i still can't get it working, though im closer.
    my problem is that i use a wrapper node(AdapterNode) to wrap Node objects. Inside the AdapterNode is an icon field that gets initialized, then changed dynamically during the execution of the app. Through debuggin over the past 13 hours(ugh), i've found my root problem: the JTree re-renders ALL of its nodes everytime an event is fired. When this happens, it recurses down the tree, and reinitializes all of my icons. (The icons get initialized in the AdapterNode constructor. there is not other place to do this because of the recursion)
    I notice that 2 event listeners get registered with my custom TreeModel.
    I was thinking about setting a boolean flag for an initial render of the tree, then mark it false and have it update only specific nodes. any suggestions?
    thanks.
    -karl

  • JTree Updating question

    Hi there. I have two questions.
    I have a data structure that is being displayed in a JTree, so I made a Model and it works great. The data structure can be updated from non-gui interaction. The nodes don't change position or anything, its just the data that is displayed is changed. I handle it currently by calling a function in the model I made called nodesChanged(), which basically does the following:
    public void nodesChanged()
        int len = treeModelListeners.size();
        TreeModelEvent e = new TreeModelEvent(this, new Object[] {rootItem});
        for (int i = 0; i < len; i++) {
          ( (TreeModelListener) treeModelListeners.elementAt(i)).treeNodesChanged(e);
      }It does actually work, the changes are reflected in the JTree, but it seems a little expensive, and the updates to the actual data model could come at about 150 per second. To deal with that now, I just use a timer class that updates it about every 3/10's of a second, which does a pretty good job, but is there a more elegant way to do this? Something where the node is an observer of the data in the data structure (which are Observable objects)?
    The second question I have is when I do the above, sometimes the display name of the node will be larger than the value it had previously, but the Textbox (if that's what it is) doesn't grow, so I get a ... at the end.
    For example, if I have "Run" and it changes to "Stopped", it will show up as "Sto...".
    Any help would be great. TIA.

    well, you can start by making the node you put in the tree model event the lowest node in the tree that needs updating, instead of root.
    I don't know about the timer thing, cuz as far as I know, the listener will invoke code that will refresh the renderers, as opposed to painting where repaint calls can be merged into one. If you aren't getting that many updates all the time, you could implement something where the listener fires to an intermediate listener which will fire the info to the tree after a slight delay. That way if you get multiple updates, you can effectively ignore lots of them.
    The ... thing, I thought that treeNodesChanged was the appropriate method, although maybe it has to be for the specific node, not root.

  • JTree update problem

    Hi,
    I have created a JTree using the vector constructor. The hierachy is a teamList(Vector) -> team(Vector) -> players(Object). I put the teamList into the JTree construcotr.
    At various points in the program the user can add teams to the team list, or players to an existing team. This is no problem. However the JTree does not update when the structure is changed.
    I have found that it is updated if the tree isnt expanded, but once expanded it doesnt get updated. I have tried calling treeDidChange(), revalidate() and loads of other methods which sound like they might do the trick! but no success. I'm sure there must be a way of doing this and that I'm just missing the point!
    Do I need to add the data to the vectors some other way? Any suggestions are greatfully received. I've spent far too long on this already!

    What about separating the UI from the program logic and data? Perhaps the JTree shouldn't hold the data, just a representation of the data.

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

  • Dynamic JTree; updating the Jtree during app execution

    I have a JTree that renders a DOM Tree. All is well. I can set different icons in the tree depending on the type of node. The functionality I need is to dynamically change the icon in the JTree for a given node. I have a wrapper object that extends DefaultMutableTreeNode and contains an Icon member varrialbe. The problem is that this varriable is initialized by a custom TreeCellRenderer depending on the contents of the node.
    I have also tried having a node_status flag inside my wrapper node, to give the Cell Renderer something to check to determine what to make the icon. The problem, I think, is that the JTree gets rerendered everytime an AWT event is fired; rerendering the JTree causes my wrapper nodes to be reinstanticated thus clearing all information in the Node, including the node_status flag.
    Has anyone done anything similar, or does anyone have any insight into what is going on?
    thanks.
    -karl

    I have figured out my problem and am posting it in the hopes that it helps others.
    I created a custom TreeModel to deal with taking an XML (DOM) Tree and rendering it in a JTree. The problem comes from the custom class that I created to wrap the DOM nodes. The geometry for the DOM tree is contained in the DOM Node (getChild(x), an XML Tree is really just a single node with children, etc) and the problem stems from the wrapper object not knowing about the geometry of the tree except by traversing the tree through the DOM Nodes; since the DOM Node is a member of the wrapper node, traversal through the DOM tree breaks any data stored in the wrapper node which is reinitialized whenever you try to get a node's child.
    Solution:
    Do not render the tree recursivly with the DOM Nodes: render the tree itteratively with wrapper nodes. Because of the frequency the JTree gets redrawn, and thus the TreeModel gets hit with events, maintaining a semi-static tree will keep the information in the nodes.
    -Karl

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • Displaying a trie in a JTree

    I've thrown together a really simple class implementing a Patricia trie (see http://hissa.nist.gov/dads/HTML/patriciatree.html) for auto-completion of words. What I now want to do is display the trie in a JTree view. The problem I'm encountering is that the trie is mutable, and I need it to update whenever a new word is inserted into the trie (possible causing a node to split e.g., inserting "application" causes the "apple" node to split into "appl" with children "e" and "ication"). Nothing I've tried so far makes the JTree update properly.
    Can someone suggest a way of solving this? I'm just putting together the JTree representation for a friend as a way of representing the trie visually, and I don't want to spend too much time on this if someone's already got a simple solution.
    Thanks,
    R. Tony Goold

    I use subclasses of DefaultMutableTreeNode for the nodes in my JTrees and I use subclasses of DefaultTreeModel as the controller for the JTrees. Whenever the tree model changes the tree's structure, it calls the appropriate method whose name is something like "nodeChanged". That's the simple solution. If that doesn't sound familiar to you, look at the tutorial here:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • JTree: how to rename or substitute folders/leafs ?

    Try to work with JTree …
    Tutorial and api description is not really clear.
    Could someone tell me:
    1. How can I change name of root or any folder/leaf from my program?
    2. How can I substitute the whole showed tree or some part of it, without deleting JTree object(since it is visible in my JPanel)?
    Thank you very much.

    You change the TreeModel which will fire the correct event so the JTree updates automatically.
    See DefaultTreeModel insertNodeInto, removeNodeFromParent and valueForPathChanged (note that you need to override this method and call nodeChanged() yourself if your tree nodes don't have String user objects.

  • JTree Render Problem

    Hi!
    In my application I have a JTree component, wich has nodes and childs. When the application starts up I populate the JTree with some data retrieved from a database. But after that I need to change some data in the database wich is reloaded and this changes the text inside the nodes in the JTree. Then I call the repaint() method of the JTree update. The problem is when the updated string is bigger then the old string, part of the string is not visible i.e it shows "..." after the text.
    Is there someone who knows this problem?
    Thanks in advance.

    Hi dayanandabv ! Thanks for your reply ! I tried your suggestion, but it won't work! i tried validate() afler and before the repaint method.
    Any other ideas?
    I'm trying hard to fix this but with no results :( some help will be appreciated.
    Thanks again.

  • JTree - make visible new node

    I have added a new DefaultMutableTreeNode, as follows, to a JTree:
    DefaultMutableTreeNode root;
    jTree = new JTree(root);
    DefaultTreeModel treeModel = new DefaultTreeModel(root);
    DefaultMutableTreeNode node = new DefaultMutableTreeNode();
    treeModel.insertNodeInto(node, root, root.getChildCount());
    now I want to display this new node in the JTree at run time (i.e. JTree updates and displays new node within GUI).
    (the JTree is within a JScrollPane).
    I have tried methods makeVisible(.), setPathToVisible(.) without success.
    What is the easiest way to do this?
    thanks in advance.

    I've used JTree.scrollPathToVisible(TreePath)

  • Need help with updateing a JTree

    I have a JList, and JTree which mimic each other. User makes selection in list presses OK and in the JTree I need the node that matches their selection to update and have child nodes under it. Can't seem to get it working right.
    right now I have this:
    Logic Trail
      item one
      item two
      item three
      item four
    after update I need this
    Logic Trail
      item one
         testing
      item two
      item three
      item four
    // in the GUI
    // pass the selected int to the method in class TreePanel
    treePanel.updateTree( questionList.getSelectedIndex());
    // here is the TreePanel class
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class TreePanel extends javax.swing.JPanel {
      private String[] questions;
      DefaultTreeModel treeModel;
      DefaultMutableTreeNode root;
        public TreePanel(String[] questions) {
        this.questions = questions;
        root = new DefaultMutableTreeNode("Logic Trail");
        treeModel = new DefaultTreeModel(root);
        initComponents ();
      private void initComponents () {
      jScrollPane1 = new javax.swing.JScrollPane ();
      logicTree = new JTree(treeModel);
      setLayout (new java.awt.BorderLayout ());
        jScrollPane1.setViewportView (logicTree);
      add (jScrollPane1, java.awt.BorderLayout.CENTER);
    // method to update JTree, when user selects accept tree will update with new logic path
    public void updateTree(int selectedNode){
      DefaultMutableTreeNode newNode = new DefaultMutableTreeNode( treeModel.getChild(root, selectedNode));
      logicTree.setSelectionRow(selectedNode);
      DefaultMutableTreeNode logicNode = new DefaultMutableTreeNode( logicTree.getSelectionPath() );
      DefaultMutableTreeNode testNode = new DefaultMutableTreeNode(" testing" );
      treeModel.insertNodeInto(testNode, logicNode, 0);
      treeModel.reload();
    public void createTree(){
      for( int i = 0; i < questions.length; i++ ){
      DefaultMutableTreeNode questionNode = new DefaultMutableTreeNode( questions[i] );
      treeModel.insertNodeInto(questionNode, root, i );
    treeModel.reload();
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree logicTree;
    // End of variables declaration
    }

    Thanks for nothing

Maybe you are looking for

  • Can't Print/Connect from Windows 7 to Shared PSC 1315 on XP Machine

    I have an HP PSC 1315 connected to a Windows XP (32 bit) machine.  This printer is shared.  I can access it from other XP machines on my home network.  I cannot access it from my Windows 7 (64 bit) machine.  I can see the printer is shared on the mac

  • Disable "Windows is checking for a solution..."

    Vista and many applications, including IE7, exist in a fragile relationship wherein the applications crash for many reasons. Vista has the truly annoying response "Windows is checking for a solution...". Is there any way to disable this functionality

  • I can sync but not stream

    ATV is successfully linked to itunes library, all music content synced over. I don't wish for all my videos to be synced to the apple tv, so it is set for custom sync with the box to show only synced items on the apple tv -unchecked- The movie that i

  • My mum's phone number has been changed without not...

    I would really appreciate some advice. My mother's phone number suddenly changed a few days ago. BT says it will take weeks to get it changed back, and tell her that she has to reapply as a new customer and set up a new direct debit agreement. She's

  • Trouble converting MOV to WMV

    I have QT Pro 7.5 running on a new Mac. Have to convert a very large MOV file to WMV. Used the export selection and changed settings to WMV. File converted but only about a minute's worth of a 40 minute presentation. Tried several times and still onl