Refresh JTrees

Hi guys,
I am currently working a project which required me to implement three different hierarchy structure and use combobox to choose between them. I am able to construct three trees and able to display individual correctly. But I have difficulty to refresh the hierachy tree by choose another combobox choice. I would be appreciated if some one can give me a simple examples to show how do I do it.
i.e. I had three combobox color, sport and food. also three corresponding hierachy, at each time only one hierarchy can be displayed by choosing one of the combobox.
Thanks very much

/* declaration of JTree */
DefaultMutableTreeNode myTreeTopNode = new DefaultMutableTreeNode("Root");
DefaultTreeModel myTreeModel = new DefaultTreeModel(myTreeTopNode);
JTree myTree = new JTree(myTreeModel);
//do your change on tree
/* reload the tree */
myTreeModel.reload();Bye
Monica

Similar Messages

  • Problem in refreshing JTree inside Jscrollpane on Button click

    hi sir,
    i have problem in refreshing JTree on Button click inside JscrollPane
    Actually I am removing scrollPane from panel and then again creating tree inside scrollpane and adding it to Jpanel but the tree is not shown inside scrollpane. here is the dummy code.
    please help me.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class Test
    public static void main(String[] args)
         JFrame jf=new TestTreeRefresh();
         jf.addWindowListener( new
         WindowAdapter()
         public void windowClosing(WindowEvent e )
         System.exit(0);
         jf.setVisible(true);
    class TestTreeRefresh extends JFrame
         DefaultMutableTreeNode top;
    JTree tree;
         JScrollPane treeView;
         JPanel jp=new JPanel();
         JButton jb= new JButton("Refresh");
    TestTreeRefresh()
    setTitle("TestTree");
    setSize(500,500);
    getContentPane().setLayout(null);
    jp.setBounds(new Rectangle(1,1,490,490));
    jp.setLayout(null);
    top =new DefaultMutableTreeNode("The Java Series");
    createNodes(top);
    tree = new JTree(top);
    treeView = new JScrollPane(tree);
    treeView.setBounds(new Rectangle(50,50,200,200));
    jb.setBounds(new Rectangle(50,300,100,50));
    jb.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
              jp.remove(treeView);
              top =new DefaultMutableTreeNode("The Java ");
    createNodes(top);
              tree = new JTree(top);
                   treeView = new JScrollPane(tree);
                   treeView.setBounds(new Rectangle(50,50,200,200));
                   jp.add(treeView);     
                   jp.repaint();     
    jp.add(jb);     
    jp.add(treeView);
    getContentPane().add(jp);
    private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode book = null;
    category = new DefaultMutableTreeNode("Books for Java Programmers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Tutorial Continued: The Rest of the JDK");
    category.add(book);
    book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs");
    category.add(book);
    book = new DefaultMutableTreeNode("Effective Java Programming Language Guide");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Programming Language");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Developers Almanac");
    category.add(book);
    category = new DefaultMutableTreeNode("Books for Java Implementers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Virtual Machine Specification");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Language Specification");
    category.add(book);
    }

    hi sir ,
    thaks for u'r suggession.Its working fine but the
    properties of the previous tree were not working
    after setModel() property .like action at leaf node
    is not working,I'm sorry but I don't understand. I think you are saying that the problem is solved but I can read it to mean that you still have a problem.
    If you still have a problem then please post some code (using the [code] tags of course).

  • How to Refresh JTree if a file System got changed during Run-time

    Hi,
    Can anyone tell me how to refresh a JTree(javax.swing.JTree) used for displaying file system(both local and remote).
    I'm getting a problem if a file/directoy is added to the file system, after my Applet is loaded. Actually, i have used DefaultTreeModel's reload() method for refreshing and calling it inside SwingUtilities.invokeLater() using Thread, but its not working.
    I want that the tree should reflect the latest Files/Directories on the click of a node, if any file or directory is added under that node.
    Plz tell me if this is possible or not.
    Thanks

    Hi Shay_te,
    Thanx for ur reply as i was eagerly waiting for the one.
    but the example is using the TreeTable
    and i have used JTree and DefaultTreeModel.
    I'm calling reload(node) within treeExpand() method
    Then, i'm regestring addTreeModelListener() as
    m_model.addTreeModelListener(new javax.swing.event. TreeModelListener(){ }
    inside which all 4 methods are over-ridden
    code snippet is as follows so plz help me and tell if this the right way:
    class DirExpansionListener implements TreeExpansionListener{
            DirExpansionListener(){
            public void treeExpanded(TreeExpansionEvent event) {
                final DefaultMutableTreeNode node = getTreeNode(event.getPath());
                final FileNode fnode = getFileNode(node);
                Thread runner = new Thread() {
                    public void run() {
                        if (fnode != null && fnode.expand(node)) {
                            Runnable runnable = new Runnable() {
                                public void run() {
                                    try{
                                       m_model.reload(node);
                                        m_model.addTreeModelListener(new javax.swing.event.TreeModelListener() {
                                            public void treeNodesChanged(javax.swing.event.TreeModelEvent evt) {
                                            public void treeStructureChanged(javax.swing.event.TreeModelEvent evt) {
                                                System.out.println("Path of node changed->"+evt.getTreePath());
                                            public void treeNodesInserted(javax.swing.event.TreeModelEvent evt) {
                                                System.out.println("Nodes Inserted method called..");
                                            public void treeNodesRemoved(javax.swing.event.TreeModelEvent evt) {
                                        System.out.println("Run inside DEvent called..");
                                        //Thread.sleep(500);
                                        //fnode.expand(node);
                                    }catch(Exception e){System.out.println("err :" +e);}
                            SwingUtilities.invokeLater(runnable);
                runner.start();
            public void treeCollapsed(TreeExpansionEvent event) {}
        Please reply...

  • Refresh JTree keep node x-y position

    Hi,
    I have a JTree which is the folders of the file system. Over time, new folders added/deleted before/after a selected node, so I need to refresh it. How to keep the selected node at the same x-y location of the view?
    I can keep the selected node in the view (visible), but the x-y position may change.
    Any information would be appreciated. Thanks in advance.

    Without seeing any code, tha best I can offer is
    -- before refreshing, store the visible rectangle and the location of the selected node
    -- after refreshing, obtain the location of the selected node and compute the offset
    -- compute the new desired visible rectangle and scrollRectToVisible
    To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • Refreshing JTree with a customized TreeModel

    Hello,
    I'm newer to Swing, and I'm seeking for help for a JTree problem.
    I hoped to display an XML document with JTree. So I customized a TreeModel and TreeNode to handle the XML data.
    I used DOM to handle XML, and define TreeNode with the following class:
    class DOMtoTreeNode {
    org.w3c.dom.Node domNode;
    public DOMtoTreeNode(org.w3c.dom.Node myNode){
    this.domNode = myNOde; }
    public String toString() {
    //the displaying code
    //and other necessary code to handle children of domNode
    Then I defined an implementation of the TreeModel Interface.
    public class DomTreeModel implements javax.swing.tree.TreeModel
    Document document;
    public DomTreeModel(Document aDomDoc){   
         this.document = aDomDoc;
    // Basic TreeModel operations
    I didn't define any personal TreeModelListener for this TreeModel
    and then I created a JTree object to display the XML tree
    treeModel = new DomTreeModel(someDOMDocument);
    treeInputParameter = new JTree( treeModel );
    and I defined JtreeListener.
    What I hoped to do is to make modification for the XML document in the JTree.
    I added the editing functions in the "valueChanged" function. I added a new DOM node as a child of an existing element node by directly append the child in the DOM node. The code is like the follows:
    DOMToTreeNode treeNodeSelected =(DOMToTreeNode)
    treeInputParameter.getLastSelectedPathComponent();
    org.w3c.dom.Node domNode = treeNodeSelected.getNode();
    //get the dom node from Jtree Node here
    domNode.appendChild(someChildDomNode);
    Up to now, it seems work fine. The TreeModel updates the DOM Document, and the modification being shown in JTree.
    But when I tried to replace an existing node with a new node, something went wrong.
    domNode.replace(newChild, oldChild);
    I debugged the code, and found the underlying DOM Document in the TreeModel had been successfully changed, but the TreeModel didn't update the display in JTree.
    I'm afraid this is quite a naive question, but would someone be kindly help me deal with this? It seems that the reason is that some code is missing to let the TreeModel refresh the frontend JTree display. But I realy don't know how to tackle this.
    Thanks!
    Haoxiang Xia

    Thank you for your reply.
    Are you adding nodes or just expanding the JTree?Adding nodes (I also want to delete nodes)
    I don't know how to do this by just implementing
    TreeModel. This is using DefaultTreeModel.Yeah, I really don't want to use DefaultTreeModel because I would have to wrap my data objects as TreeNodes. Since my data objects are already in a tree structure, implementing TreeModel is much cleaner.
    It looks like I have to implement fireTreeNodesInserted() in my TreeModel, but I guess what I need to understand is how to register the JTree as a listener to my custom TreeModel. JTree doesn't directly implement TreeModelListener. I read somewhere that JTree automatically registers itself with the TreeModel, but that is not what I am observing.
    So..., I am still in need of more info.

  • Refreshing JTree

    I am trying to develop a file explorer for my homework.
    I have a JComboBox which lists the drives in the system.
    I have a JTree in JScrollPane which has to display the contents
    of the chosen drive.
    I have the JTree working the first time. But when I change the drive
    in JComboBox, how would I make the JTree to change
    to show the contents of new drive?
    All I have for now is to capture the comboBoxChanged event and
    find the drive the user has chosen. How should I proceed to
    refresh the JTree?
    Thanks in advance for your help.
    Matt

    Again answering my own post...
    Found the answer! Just so it will be useful for others who search,
    call to <JTree Object>.updateUI() solved this problem
    Matt

  • Unable to refresh JTree

    Hi!
    I am using a TreeModel to manage the content of a JTree.
    I provide buttons to add/remove items in the tree. The content is correctly modified (when I do some System.out.println(...)), but I don't see the new items on my displayed tree.
    I tried to use
    JTree.revalidate();
    JTree.repaint();
    And the same on the panel containing the JTree, nothing works!
    What should I do?
    Thanks a lot
    Choub

    Hi,
    you can try with this sample code:
    * <p>Adds a new objects in the JTree. </p>
    * @param parent - the DefaultMutableTreeNode parent
    * @param child - the object to add
    * @param shouldBeVisible - if it is true, all the path components in path
    * are expanded and scrolls so that the
    * node identified by the path is displayed.
    * @return a DefaultMutableTreeNode object
    * @see javax.swing.tree.DefaultMutableTreeNode
    public DefaultMutableTreeNode addObject( DefaultMutableTreeNode parent,
    Object child,
    boolean shouldBeVisible) {
    DefaultMutableTreeNode childNode = null;
    switch ( this.levelSelected ) {
    case 0: childNode = new DefaultMutableTreeNode(
    new IconData( rm.getIcon("db/Computer.gif"), child ) );
    break;
    case 1: childNode = new DefaultMutableTreeNode(
    new IconData( rm.getIcon("db/BCard.gif"), child ) );
    break;
    case 2: childNode = new DefaultMutableTreeNode(
    new IconData( rm.getIcon("db/Thread.gif"), child ) );
    break;
    if ( null == childNode )
    return null;
    if ( null == parent ) {
    parent = root;
    model.insertNodeInto( childNode, parent, parent.getChildCount() );
    model.reload();
    if ( shouldBeVisible ) {
    logicTree.scrollPathToVisible( new TreePath( childNode.getPath() ) );
    return childNode;
    Regards.

  • Can't collapse treepath after setmodel method

    Hi
    I'm writing app client for my ejb modules. I have entity bean named Category, and I want navigate through them using JTree. Everything is ok, but when I add new category in my app, I'm refreshing JTree and I'm loosing my selection path - all nodes are collapsed. That's my code (only add method):
    javax.swing.tree.TreePath treePath = categoryTree.getSelectionPath();
    javax.swing.tree.DefaultMutableTreeNode treeNode = (javax.swing.tree.DefaultMutableTreeNode)categoryTree.getLastSelectedPathComponent();
    CategoryTreeNode categoryTreeNode = (CategoryTreeNode)treeNode.getUserObject();
    int categoryId = categoryTreeNode.categoryId;
    if(categoryNameText.getText().length() == 0)
    return;
    new CategoryCreate(categoryId, categoryNameText.getText());
    categoryTree.setModel(new CategoryTreeObject().jTree.getModel()); // here I acquire new jTree (with added node) and swap models in my jTree which is displayed
    categoryTree.setSelectionPath(treePath);
    categoryTree.expandPath(treePath); // should it work here?
    Thanks,
    Michael

    Presumably when you create a new tree model it contains new DefaultMutableTreeNodes?
    Since your selected path is defined by "old" tree nodes and your new model has "new" tree nodes the old path doesn't match a path in the new model.
    I think DefaultMutableTreeNode doesn't use the user object to determine equality. If you're confident that your user object uniquely identifies the node then you could subclass DefaultMutableTreeNode to use that user object in its equals method.
    Ideally you'd get your model to reload only the bit you're interested in (ie, mutate it - as the name suggests!).
    Hope this helps.

  • Refreshing the jtree in a jpanel

    hi,
    i created a jtree of files in a certain folder... if some files changed in my folder, how can i refresh the jtree in my jpanel...
    thanks!!!

    Hi,
    look here:
    http://forum.java.sun.com/thread.jspa?threadID=478780&messageID=2226565
    L.P.

  • How can i refresh a jtree using DefaultMutableTreeNode?

    I already create a jtree using DefaultMutableTreeNode, and i also could implement to it the addMouseListener to do a action when the user press every node......Also i used the following instruction to remove all nodes: root_tree.removeAllChildren(); and it instruction remove all the nodes....but when i :
    fill the tree
    compile my program
    i see the tree in my jpanel....it is Ok!
    now.....
    fill the tree
    remove the tree
    compile my program
    i see only the root (this i wish) it is Ok!
    But now i would like that after that i press a combo element (in the actionperformed method):
    remove the tree
    fill the three with the new nodes
    show the tree
    But my tree always is the same :(......is like it to need a repaint ....but i already implement it...but i obtain the same result.....
    Do somebody have any suggestion...or idea how i can do a refresh in my jtree?....
    Anybody could help me please?
    Thanks in advance.....
    Mary

    Construct your tree like this:DefaultMutableTreeNode rootNode = xxx;
    DefaultTreeModel model = new DefaultTreeModel( rootNode );
    JTree tree = new JTree( model );When you update the root node, just tell the model to fire the appropriate change event by doing this:model.reload( rootNode );or this:model.nodeStructureChanged( rootNode );or this:model.setRoot( rootNode )

  • JTree - changed content, refresh

    Hello,
    I have a problem in my program I can`t solve...
    basically I am using drop-down menu with different drives (c:, d:, etc.). Don`t ask me why I don`t use the JTree to display all the drives, I simply need to display each drive separately.
    when I select the drive, JTree pops up with the content of the drive.
    Problem comes in, when the JTree is already displayed and I go into my drop-down menu to select a different drive.... Everything seems to work fine in background.... The tree gets build up, I just somehow cannot update (or refresh) the screen....
    did anyone experienced similar problem?
    thank you
    Otakar

    No, I am not using TreeModel.. Let me post the code... I am using 3 different files:
    MainModule.java
    DetectDrives.java
    FileSystem.java
    I think You might wanna see the ChoiceListener in MainModule
    thank you for you time
    MainModule.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.*;
    import java.awt.event.*;
    public class MainModule{
         private JFrame aFrame;         // BASE frame
         private JPanel driveListPane;
         private JList  driveList;
         // MENU Bar Components
         private JMenuBar aMenuBar;
         private JMenu fileMenu, editMenu, viewMenu, settingsMenu, helpMenu;
         private JMenuItem newMenuItem, openMenuItem, saveMenuItem,                // FILE menu Items
                                           saveAsMenuItem, exitMenuItem,                     //
                                           selectDriveMenuItem, selectOutputMenuItem;        // SETTINGS menu Items
          // ComboBox
         private JComboBox aComboBox;
          // Buttons
         private JButton selectDriveButton, printButton;
         // Listeners
         private PrintButtonListener prtListener;
         private ChoiceListener choiceListener;
         // Labels
         private JLabel sourceLabel, label1, label2;
         private int listRows;
         public static String drive;
         private DetectDrives dd;
         private FileSystem fs;
         private int ct;
         /*============ CONSTRUCTOR ===========================================================\
         |
         public MainModule(){
             ct = 0;
              // create a MAIN WINDOW (Frame)
              drive = new String("C:\\");
              aFrame = new JFrame("Otax Drive Printer 0.99b");
              aFrame.setSize(800, 600);
              aFrame.setLocation(100, 50);
              aFrame.getContentPane().setLayout(null);
              aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // create the categories in a menu bar
              aMenuBar = new JMenuBar();
              fileMenu = new JMenu("File");
              editMenu = new JMenu("Edit");
              viewMenu = new JMenu("View");
              settingsMenu = new JMenu("Settings");
              helpMenu = new JMenu("Help");
              // create menu items for FILE menu
              newMenuItem = new JMenuItem("New", 'N');
              openMenuItem = new JMenuItem( "Open", 'O');
              saveMenuItem = new JMenuItem( "Save", 'S' );
                     saveAsMenuItem = new JMenuItem( "Save As", 'A');
                     exitMenuItem = new JMenuItem("Exit", 'E');
              // create menu items for SETTINGS menu
                     selectDriveMenuItem = new JMenuItem("Select Drive", 'D');
                     selectOutputMenuItem = new JMenuItem("Select Output", 'O');
              // detect drives mounted to system and put them into JComboBox
              dd = new DetectDrives();
              aComboBox = new JComboBox(dd.detectCdDrives());
              aComboBox.setBounds(100, 5, 180, 20);
              //create labels
              sourceLabel = new JLabel("Select Source:");
              sourceLabel.setBounds(6, 4, 90, 20);
                     label1 = new JLabel("Current Drive: ");
              label1.setBounds(2, 500, 90, 20);
              label2 = new JLabel();
              label2.setBounds(85, 500, 50, 20);
              //create buttons
              printButton = new JButton("Print");
              printButton.setBounds(2, 50, 101, 16);
                     //create Accelerators for FILE MenuItems
                     newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_N, InputEvent.CTRL_MASK, false));
              saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_S, InputEvent.CTRL_MASK, false));
              //create the action listeners (listener definitions bellow)
              prtListener = new PrintButtonListener();
              choiceListener = new ChoiceListener();
              //connect the action listeners with menu items
              printButton.addActionListener(prtListener);
              aComboBox.addActionListener(choiceListener);
         // LISTENERS Definitions start HERE ====================================
         public class PrintButtonListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   System.out.println("print action performed: " + drive);
         public class ChoiceListener implements ActionListener{
             public void actionPerformed( ActionEvent e)
                  ct++;
                  System.out.println(ct + " event started");
               String drive = new String(aComboBox.getSelectedItem().toString().substring(0,2));
               label2.setText(drive);
               fs = new FileSystem(drive + "//");
               fs.sortFiles();
               fs.addNodes(drive);
               DefaultMutableTreeNode top = fs.getNodes();
               JTree tree = new JTree(top);
               tree.setBounds(10, 30, 500, 450);
                  aFrame.getContentPane().add(tree);
               aFrame.repaint();
         public void addComponents(){
              aMenuBar.add(fileMenu);        // create menu
              aMenuBar.add(editMenu);
              aMenuBar.add(settingsMenu);
              aMenuBar.add(helpMenu);
              fileMenu.add(newMenuItem);     //add items to the FILE menu
              fileMenu.add(openMenuItem);
              fileMenu.addSeparator();
              fileMenu.add(saveMenuItem);
                     fileMenu.add(saveAsMenuItem);
                     fileMenu.addSeparator();
                     fileMenu.add(exitMenuItem);
              settingsMenu.add(selectDriveMenuItem);
              settingsMenu.add(selectOutputMenuItem);
              aFrame.setJMenuBar(aMenuBar);
              aFrame.getContentPane().add(aComboBox);
              aFrame.getContentPane().add(sourceLabel);
              aFrame.getContentPane().add(label1);
              aFrame.getContentPane().add(label2);
              aFrame.setVisible(true);
         public static void main(String [] args){
              MainModule m1 = new MainModule();
              m1.addComponents();
    DetectDrives.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.filechooser.*;
    public class DetectDrives{
         private FileSystemView fsv;
         private File[] roots;
         private Vector drives;
         /*======== CONSTRUCTOR =====================================================================\
         |Purpose: To INITIALIZE the object                                                          |
         |Variables: (FileSystemView) fsv - creates the Object containing info about current system  |
         |           (File[]) roots - array used to store all drives currently mounted to system     |
         |           (Vector) drives - vector used for storage of selected info about drives         |
           \==========================================================================================*/
         public DetectDrives(){
              drives = new Vector(0,1); // *Create empty Vector(0) with expansion capacity (1)
              //--- Get a FileSystemView object for the current system
             fsv = FileSystemView.getFileSystemView();
            //--- Get an array of File objects describing the 'roots' attached to the system
              roots = File.listRoots();
         /*SD1)==== Method detectCdDrives() ========================================================\
         |Purpose: To SCAN the system for any drives mounted and add DRIVE LETTER and DRIVE NAME    |
         |         to a Vector. It Also CHECKS if drive CONTAINS any DATA or if it`s EMPTY.         |
         |Variables: (int) i - a loop iterator                                                      |
         |           (String) cdInfo - temporary storage for drive information during drive check   |
         |           (Vector) drives - storage for driveletter and drive name for all drives        |
         |                             This Vector is returned upon function call                   |
         public Vector detectCdDrives(){
              String cdInfo;
              //SCAN system and RETRIEVE drives
              for(int i = 0; i < roots.length; i++){
                   if((fsv.getSystemDisplayName(roots)).equals("")) //--FIND OUT if any DATA on DRIVE
                        cdInfo = fsv.getSystemTypeDescription(roots[i]) + " ";
                   else
                   cdInfo = fsv.getSystemDisplayName(roots[i]);
                   drives.addElement(roots[i].getPath() + " " + cdInfo.substring(0, cdInfo.length()-5));
              return drives;
    FileSystem.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.io.File;
    import java.io.*;
    import java.util.Vector;
    public class FileSystem{
         private String driveLetter;
         private Vector root;
         private Vector dirs;
         private Vector files;
         private File dir;
         private File [] allFiles;
         private DefaultMutableTreeNode top;
         /*================= File System Constructor ================================\
         |Purpose: To initialize the conject and to accept drive letter selected in  |
         |         main module                                                       |
         public FileSystem(String dl){
              driveLetter = dl;
        /*================= Method: sortFiles() ====================================\
         |Purpose: To sort content of selected drive, directories (alphabetically),  |
         |         followed by files (alphabeticaly)                                 |
         public void sortFiles(){
              dir = new File (driveLetter);
              allFiles = dir.listFiles();
              root  = new Vector(2,1);
              dirs  = new Vector(0,1);
             files = new Vector(0,1);
             //---- Separate Directories and Files into 2 different vectors
             for(int i = 0; i < allFiles.length; i++){
                   if(allFiles.isDirectory())
                   dirs.add(allFiles[i]);
                   else
                   files.add(allFiles[i]);
              //---- Add elements from dirs and files Vectors into root vector
              for(int i = 0; i < dirs.size(); i++){
                   root.add(dirs.elementAt(i));
              for(int i = 0; i < files.size(); i++){
                   root.add(files.elementAt(i));
    /*================= Method: addNodes() =====================================\
         |Purpose: to build the file structure which will be used to create the tree |
         |Variables: drive = used to accept the drive letter representing the root |
         | top = primary (root) node in the structure) |
    | root = vector of all files in the drive |
         public void addNodes(String drive){
              top = new DefaultMutableTreeNode(drive);
              DefaultMutableTreeNode node = null;
              for(int i = 0; i < root.size(); i++){
                   node = new DefaultMutableTreeNode(root.elementAt(i));
                   top.add(node);
    /*================= Method: getNodes() =====================================\
         |Purpose: To return variable top, which holds the files structure and will |
         | be used to build the tree |
    public DefaultMutableTreeNode getNodes(){
              return top;

  • Problem in refreshing a JTree

    Hi,
    Can anyone tell how to refresh a JTree(javax.swing.Jtree) used for displaying file system(both local and remote).
    I'm getting a problem if a file/directoy is added to the file system, after my Applet is loaded. Actually, i have used DefaultTreeModel's reload() method and calling it inside SwingUtilities.invokeLater() using Thread, but its not working.
    Plz help me out.
    Thanks

    Hi everybody,
    CAN ANYONE HELP ME OUT?????????

  • JTree refresh probleme help me please

    a can't reload my JTree from my server
    my Jtree code:
              user.add("Zeus@mxf");
              user.add("Neptune@toto");
              user.add("Ulysse@mars");
         root =new DefaultMutableTreeNode("users");
              for(int i=1; i<user.size(); i++)
              userNode = new DefaultMutableTreeNode
    (user.elementAt(i) );
                   root.add(userNode);     
              renderer.setOpenIcon(OpenIcon);
         renderer.setClosedIcon(ClosedIcon);
         renderer.setLeafIcon(PrinterIcon);
              tree=new JTree(root);
              tree.setCellRenderer(renderer);
    and if a have receive the write data i do my refresh methode:
    refresh()
    userNode = new DefaultMutableTreeNode(user.elementAt(0) );
                                  root.add(userNode);     
                                  ((DefaultTreeModel)tree.getModel()).reload();
                                  tree.treeDidChange();
                                  tree.setCellRenderer(renderer);
                                  tree.setLargeModel(true);     
                                  tree.repaint();
                                  tree.revalidate();
    why it dose not work ?????

    Sorry I have not ready examples, try to implement a method this way:
    String newUser = user.elementAt(0);
    public void addNode(String newUser){
    DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(newUser);
    root.add(userNode);
    tree.getModel().nodeChanged((TreeNode)tree.getModel().getRoot());
    tree.treeDidChange();

  • JTree expandAll - refresh after each expandPath?

    I'm using a JTree with about 1000 nodes under the not visible root node. All of these nodes have one or more children.
    The "collapse/expand all" works fine (both algorithms listed in other topics), but it refreshes the whole view after each expandPath was called.
    I've tried to overwrite the fireTreeExpanded/Collapsed in my tree in order to block the swing update and after each expandPath call and finally refresh the tree but I could not do that.
    The in/revalidate(), repaint(), etc. and DefaultTreeModel.nodeStructureChanged and co. had not worked.
    The only thing what seems to work is the updateUI, but it ignores the the previous JTree.setRowHeight(0) setting, and because I use different fontsize in some nodes they were only partially visible.
    Any idea?

    It is a shot in the dark at this point, but previously I had problems with renaming a node and get the ellipess (...) because the renderer (JLabel) didn't have enough room to draw the full string.
    I am wondering if your issue stems from the renderer not having enough room to draw the second label in the layout for the tree.
    I know you said you are already using the model to add/remove the nodes, but assuming you are using the default model have you tried calling nodeChanged?
    ((DefaultTreeModel)yourTree.getModel()).nodeChanged( yourNode );That seems to effect the space allocated for the renderer to draw the node.

  • Refreshing a jtree(jdeveloper)

    if the tree is expanded then how can it be collapsed on a button's click event
    and if we have a value equivalent to a particular node of jtree then how we can expand the tree upto that level
    i m using jdeveloper and i have to display the in expanded form immediately after selecting a value in a jtable and when i click refresh button then tree must be collapsed

    The problem is that I'm not chaning a node directly. My custom nodes are based on a DOM Document, and I'm changing the contents of one of the document's elements using a text field. So what I need to do is inform the JTree that it needs to re-render.
    Calling treeDidChange() does force the tree to re-render, but the JLabel's at each node do not change their size - so when my renderer does a setText() for a node, the label's bounding box is still the size of the old text and I get a "..." showing that my new text is too big for the box.
    The only way I've found to solve it is to set a new renderer every time I change the model's data. However, this means I am creating tons of these render objects, one on each edit! Yuck!
    I'm sure there's a more elegant or correct way to do this.

Maybe you are looking for

  • Storage system verify or repair failed

    Had problems with Time Machine and accessing external backup drive. Both Mac Hard drive and extenal drive encrypted and external drive not opened with password. Eventually located corrupt file on external drive. Have managed to get time machine to ba

  • Electric shocks in iPhone 4 and Macbook Pro

    Hi When I first started using my white 32GB iphone 4 a month ago, I felt very slight electric shocks and static-like feeling and a kind of pins and needles feeling in my hands. I soon either forgot about it or got used to it. Then 2 weeks ago, I got

  • My Home sharing has not worked for over a year.

    My iTunes is up to date and the Home is switched on within iTunes and on my iphone (4S ios7). However, in general the iphone will not give me the option to access a shared library, only when I go on to iTunes, turn of Home Sharing and turn it on agai

  • Windows 7 (32) will not see iPhone 4S

    Right, there are loads of questions about just this issue on this and other forums and I've yet to see it answered, so I hope that we can finally sort it. I'm trying to use my iPhone 4S with a Windows 7 32-bit PC. In device manager, one can clearly s

  • I forgot my apple id security question

    I forgot my apple id security question and i tried resetting it on My Apple ID website however when i went to "Password and Security" there was no choice to reset the questions, it only asked me the answer to my security question which i forgot. Solu