JTree display

I've created a JTree held in a scroll pane which lists folders/files and was wondering if there was anyway to cut down the detail of the filepath that is displayed, i.e if you click into a folder, the files inside it only display what comes after it, not the full path from the root....

To answer the question you didn't ask and probably didn't know you should have asked:
What you see on the GUI when you use a JTree is the result of the toString() method of the objects you put into your tree nodes. For example, if you're using File objects, you see whatever File.toString() returns. So if you don't like that, write your own object (maybe a thin wrapper for File) that returns something more congenial as the result of its toString() method.

Similar Messages

  • How do I control the order in which JTree displays nodes?

    I'm trying to display the nodes in a JTree in a specific fashion, but I can't figure out how to change the order JTree displays them in. It seems the default is alphabetically, with leaves first and nodes with children second. I've spent a few hours pouring through the documentation, but I haven't been able to find out what I need to do. Anyone know?

    They are displayed in the order they are added on the same level.

  • JTree, displaying data from a database

    Hi, im doing an application that will display the listing of courses, and allow users to book them. For the display of courses, i plan to use JTree to display them.
    However my problem arises from fetchin data and putting them into the tree.
    This file connects to the database and fetch the 'Course Category' and puts it in an Array.
    public ArrayList<CourseCategory> getCategory() {
    ArrayList<CourseCategory> categoryArray = new ArrayList();
    try {
    String statement = "SELECT * FROM Category";
    rs = stmt.executeQuery(statement);
    while (rs.next()) {
    CourseCategory cc = new CourseCategory();
    cc.setCategoryID(rs.getInt("CategoryID"));
    cc.setCategoryName(rs.getString("CategoryName"));
    categoryArray.add(cc);
    rs.close();
    stmt.close();
    con.close();
    catch (Exception e) {
    //catch exception     }
    return categoryArray;
    CourseCategory File has the necessary accessor methods, and a toString method to display out the category name.
    The main file, which has the JTree
    public DisplayCoursesGUI() {
    try {
    courseDB = new CourseDB();
    courseDB.getCategory();
    catch (Exception e) {
    //catch exception }
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("");
    for (int i=0;i<courseDB.test2().size();i++) {
    category = new DefaultMutableTreeNode(courseDB.getCategory());
    top.add(category);
    Codes for JTrees as follows.
    I have the output of
    e.g.
    [MICROSOFT OFFICE APPLICATIONS, WEB APPLICATIONS] repeated twice in the tree. Im hoping to achieve the following effects
    e.g.
    -MICROSOFT OFFICE APPLICATIONS
    ----Microsoft Word
    ----Microsoft Powerpoint
    -WEB APPLICATIONS
    -----Adobe Photoshop
    I have 2 MS Access Table.[Category]ID, CategoryName. [COURSE]ID,CourseName,CategoryID. They have a relationship.
    How do I modify my codes to get what i hope to achieve? Help really appreciated.
    Thank you!!

    Hi,
    If you read my first post, I wanted to achieve this effect.
    ----CategoryName1
    ----------SubCategoryItem1
    ----CategoryName2
    ----------SubCategoryItem2
    My Table Structure.
    CATEGORY TABLE
    ID (autonumber), Name(string)
    COURSES TABLE
    ID(autonumber),Name(string), CategoryID(int)(A Relationship is link to Category Table-ID)
    I have managed to retrieve the items from the Category Table into a result set, and I have added the result set into an Array (See 1st post)
    Now, the problem comes when im tryin to do a for loop to display out the categorynames from the array(see 1st post again).
    Now my array prints out as follows
    e.g.
    [CategoryName1,CategoryName2]
    And if i put a for look into my application to display a JTREE,
    My end results is
    ------[CategoryName1, CategoryName2]
    ------[CategoryName1, CategoryName2]
    How should I ammend my codes to get:
    -------CategoryName1
    -------CategoryName2

  • Question with updating JTree Display

    Hello all,
    I have a question about how to change what a JTree is displaying. Currently I have classes called ElementTreeFrame, ElementTree, ElementTreeModel, and, of course, Element. The ElementTreeFrame is simply the frame where I store a ElementTree, it has 2 buttons (JButtons at the bottom) Add and Open. I am trying to Dynamically add an Element to my ElementTree.
    The Element class has a Vector in it, called childElements. When the user clicks Add, a new Element is added to the Vector. Let me explain a bit further. The element that is currently selected is returned via
    parentElem = (Element)parentPath.getLastPathComponent();
    Then a new Element is added by saying
    parent.childElements.insertElementAt(child, parent.getChildCount());
    which is code the Vector class provides. parent.getChildCount() simply returns the number of children present so that the child (the new Element being added) can be inserted in the right place.
    Here is my problem. When I first add an Element, it works fine. As a matter of fact, I can add as many Elements as I want and it will work fine. That is, until I manually expand the tree. When an Element is added, the tree doesn't expand. So I can add as many as I want, and it will work fine. The instant I coudlbe click on my Element to expand the tree, I can no longer insert a new Element. Technically, it gets inserted correctly, I know this because getChildCount remains correct, but the display is no longer correct. The line that extends from the folder to the new leaf is broken.
    I need to find a way to refresh my tree display. I am at a complete loss on how to do this. I have read about firingTreeNodesInserted or using reload, or a bunch of other methods but I am confused due to an overload of different methods.
    Can anyone tell me what my train of thought should be to do this? I'd just like a simple way for the nodes to be displayed correctly.
    Thank you so much,
    Nick

    Neverrmind, I figured it out. A call to to eTree.updateUI() handled it just nice.
    Thanks to myself, for being so hot.

  • JTree display: vertical connecting lines missing

    My JTree uses a subclass of TreeModel to display the contents of a DOM tree and to allow modifications on this tree. I've got a problem with the rendering of the tree: the vertical connecting lines don't show.. (also there seems to be problems with the refreshing of the tree display, even though TreeModelEvents are fired properly, but it might not be related.)
    The problem originates from the TreeModel subclass (other models worked fine), but I can't tell what exactly in the class causes it. I've tried to remove code, etc.. with no effect.
    Has anyone encountered something similar?
    Thanks in advance.
    Simon

    yeah... that's common in jtrees that do not refresh well... you know that something is wrong when the lines have dissappeared.
    when i encountered this problem what i did was to copy the lines from DefaultTreeModel sourcecode where the model is refreshed into my code... that worked fine for me...

  • JClient Jtree Display Issues

    Hi I've got a JClient JTree which is used as a navigation tool to sync a master detail form. The JTree is on a scrollable panel within the master panel.
    The JTree model has been set up as follows:
    treePanelBinding = new JUPanelBinding(panelBinding.getApplicationName(), this);
    jTree1.setModel(JUTreeBinding.createTreeNodeTypeBinding(treePanelBinding, jTree1, "DistrictView", "DistrictViewIter", "DistrictViewIter", new JUCtrlHierTypeBinding[]
    {new JUTreeAccessorTypeBinding("DistNode", "opbo.DistrictView", "DistrictDescription", "BlockView", null, null, null),
              new JUTreeAccessorTypeBinding("BlockNode", "opbo.BlockView", "BlockDescription", "AssetView", null, null, null),
              new JUTreeAccessorTypeBinding("AssetNode", "opbo.AssetView", "AssetName", "opnamedate", null, null, null),
              new JUTreeAccessorTypeBinding("OpNode", "opbo.opnamedate", "Optypedate", null, null, null, null)}));
    This has been defined in the master panel. Note that is using a seperate JUPanelBinding than the master panel i.e. treePanelBinding.
    I have also assigned a JUTreeDefaultMouseListener to this tree. Its definition is as follows.
    jTree1.addMouseListener(new JUTreeDefaultMouseListener(panelBinding,new String [][]{{"BlockNode","BlockViewIter"},{"AssetNode","AssetViewIter"},{"OpNode","opnamedateIter"}},false));
    Note that in this case the panelBinding object is the JUPanelBinding defined for the master panel.
    The navigation tree works well syncing the master detail panel, however I have a function to insert a new asset record using the AssetView from the master panel. The code to do this is as follows
    Row row = panelBinding.findIterBinding("AssetViewIter").getRowSetIterator().createRow();
    row.setAttribute("BlockId",panelBinding.findIterBinding("BlockViewIter").getRowSetIterator().getCurrentRow().getAttribute("BlockId"));
    panelBinding.findIterBinding("AssetViewIter").getRowSetIterator().insertRow(row);
    The problem I'm getting is after the above lines are executed, the record is successfully inserted but then a new node is created in the tree but it is usually under the wrong block node. However if I close the application down and restart the application, the tree displays all the asset information under the right block node.
    In summary I thought by selecting a block node in the tree and then running the above code the asset should appear under the selected block node in the tree, I can see the block is correctly set on the master panel, I know the asset record is inserted with the correct block, but the tree initially does not display the node in the right position. However if you reboot the application the tree displays everything correctly. Is there a way to ensure the tree is consistent with the underlying data?
    Thanks

    I've not tried this scenario.
    However, you may want to set your ViewObject into "association consistent mode" either by calling ViewObject.setAssociationConsistent(true) or by setting all VOs in this mode by setting the Configuration parameter "jbo.viewlink.consistent" to true.
    This sets up the framework in the mode where if new rows are inserted into one RowSet, other RowSets (on the same ViewObject type) get a chance to include the row as well provided the criteria on that RowSet is met - which in your case does not seem to be the issue as you're simply viewing two Rowsets over the same ViewObject/query.

  • JTree display problem

    Hi guys,
    I have a static JTree
    ROOT
    |
    - FOLDER 1
    | |
    | - LEAF 1
    | - LEAF 2
    - FOLDER 2
    I want to display the entire tree with full depth. I can't manage it to make the leaves visible by default.
    Need help! Thanks

    Hi guys,
    I have a static JTree
    ROOT
    |
    - FOLDER 1
    | |
    | - LEAF 1
    | - LEAF 2
    - FOLDER 2
    I want to display the entire tree with full depth. I can't manage it to make the leaves visible by default.
    Need help! Thanks

  • JTree Display keeps Repainting and Missing Information

    I have a JTree that has objects for each node. When I try to send regular Text in the toString of the object, I have no issues with the display of the Tree. When I send HTML, the screen has issues with the repaint?? I expand the Tree and some of the rows are missing.. Anyone had this experience before.
    public String toString() {
    String Display = "<html><body><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td width=\"160\">"+category+"</td><td width=\""+(MaxWidths[1]*6)+"\">"+problem+"</td><td width=\""+(MaxWidths[2]*6)+"\">"+goal+"</td><td width=\""+(MaxWidths[3]*6)+"\">"+parameter+"</td></tr></table></body></html>";
    return(Display);
    I am using tables to format the width of the columns. Does someone else use a different formating method?

    1. set the height of rows to a value of less than or equal 0 so that the renderer is used to determine the rowheight of each row (note that for rendering purposes the tree is mapped on rows. Use
    JTree.setRowHeight(0);for setting the row height.)
    2. ensure that the renderer calculates the height of each cell correctly. I think you shouldn't have to when using JLabel or subclasses as renderers...
    Regards,
    Fritz

  • Jtree display performance

    I try to display a JTree with 7 000 elements and it takes a lot of time to appear at the screen, so how can I speed up the display, my method is like this :
    DefaultMutableTreeNode rootTreeNode = DefaultMutableTreeNode)tree.getModel().getRoot();
    for(int t = 0; t != displayGenes.size(); t++) {
    current++;
    DbxrefGeneProduct dbxref = (DbxrefGeneProduct)displayGenes.elementAt(t);
    Vector vecEvidences = dbxref.getEvidences();
    DefaultMutableTreeNode dmtn = new DefaultMutableTreeNode(dbxref);
    for(int u = 0; u < vecEvidences.size(); u++) {
    //my objects
    Evidence ev = (Evidence)vecEvidences.elementAt(u);
    DefaultMutableTreeNode dmtn2 = new DefaultMutableTreeNode(ev);
    dmtn.add(dmtn2);
    rootTreeNode.add(dmtn);
    ((DefaultTreeModel)tree.getModel()).reload();

    I try to display a JTree with 7 000 elements and it takes a lot of time to appear at the screen, so how can I speed up the display, my method is like this :
    DefaultMutableTreeNode rootTreeNode = DefaultMutableTreeNode)tree.getModel().getRoot();
    for(int t = 0; t != displayGenes.size(); t++) {
    current++;
    DbxrefGeneProduct dbxref = (DbxrefGeneProduct)displayGenes.elementAt(t);
    Vector vecEvidences = dbxref.getEvidences();
    DefaultMutableTreeNode dmtn = new DefaultMutableTreeNode(dbxref);
    for(int u = 0; u < vecEvidences.size(); u++) {
    //my objects
    Evidence ev = (Evidence)vecEvidences.elementAt(u);
    DefaultMutableTreeNode dmtn2 = new DefaultMutableTreeNode(ev);
    dmtn.add(dmtn2);
    rootTreeNode.add(dmtn);
    ((DefaultTreeModel)tree.getModel()).reload();

  • JTree Display Update

    I use a JTree that requires periodic changes to its nodes. I cannot get the display of the JTree to update however. I have tried many different things such as JTree.updateUI(), DefaultTreeModel.reload(), DefaultTreeModel.nodesChanged().
    Currently my code looks like this:
    // initialization
    createTreeNodes();
    treeModel = new DefaultTreeModel(rootNode); treeModel.addTreeModelListener(this);
    tree = new JTree(treeModel);
    // code invoked whenever changes to JTree must be made
    createTreeNodes();
    treeModel.reload();
    tree.repaint();
    // this is the function "createTreeNodes"
    private void createTreeNodes()
    rootNode = new DefaultMutableTreeNode("File Name");
    DefaultMutableTreeNode headerNode = new DefaultMutableTreeNode("Header 1");
    for(int i=0; i<cardArray.size(); i++)
    DefaultMutableTreeNode cardNode = new DefaultMutableTreeNode(cardArray.get(i).getFront() + " (" + (i+1) + ")");
    // above line simply creates a node with a string
    System.out.println(cardArray.get(i).getFront() + " (" + (i+1) + ")");
    // the above line recreates the code 2 lines above for debugging purposes
    headerNode.add(cardNode);
    // above code adds child to parent
    rootNode.add(headerNode);
    // above code adds parent to root node
    }The tree is updated in createTreeNodes().
    If a file is opened by a user, cardArray changes and I reflect these changes by updating the JTree. The System.out.println() statement in the createTreeNodes() function prints the expected data to the console, which proves that the data is being updated. The display of the JTree does not update however.
    And for further explanation about my code:
    - the part that I commented "Initialization" is located in the program constructor. At this point cardArray is equal to 0, and the program simply displays one leaf node with a value of 'null'
    - If the user opens a new file, cardArray (an ArrayList) is updated. I call the createTreeNodes() function which updates the JTree data. I also call treeModel.reload() to signal to the DefaultTreeModel that its data has been updated
    - the function 'createTreeNodes()' simply adds DefaultMutableTreeNodes to the JTree hierarchy
    My thanks in advance for any help you may be able to provide.

    Hi,
    I have taken a look at your code, and I can't see that you are updating the tree. Your createTreeNodes method does only create a new root node, and stores the reference in the attribute rootNode. That does neither affect the root or the model created in the initialization block.
    /Kaj

  • JTree display issues and thread safety

    I've recently ran into some issues with a JTree not displaying correctly. Infrequently, blank space will appear in the tree (big gaps between consecutive nodes), or the text of a node will be cut off ending with a "...". This happens when (but not yet proven a direct result of) one thread is expanding a node of the tree while another thread is inserting nodes into one of the expanding node's children through calls to DefaultTreeModel.insertNodeInto. (what I'm doing here is lazy loading the children's children when the parent is expanded, and the lazy loading is performed by a seperate thread so as not to delay the main thread.) It does not happen if the second thread simply adds child nodes without using the DefaultTreeModel's insertNodeInto method.
    I think what might be happening here is that the DefaultTreeModel.insertNodeInto method is calling fireTreeNodesInserted which I think is in turn causing nodes in the tree to be re-rendered. This got me thinking that the problem may come down to the DefaultTreeCellRenderer being used by the two threads simultaneously. DefaultTreeCellRenderer extends JLabel and returns itself in the getTreeCellRendererComponent method. If two threads were causing nodes to be rendered at the same time, it would seem the rendered label could be occasionally in an inconsistent state.
    Anyone ran into a situation like this before? The problem of text being cut off seems to be eliminated by having a custom renderer return a new component each time, rather than returning itself, but this results in degraded performance. It's almost as if each thread would need it's own renderer (or the renderer would need to return a different component for each thread), but I'm not sure how this would be done. And this doesn't solve the problem of gaps appearing in the tree.
    As for the gaps, I think this might be solved by changing when the children's children are getting loaded in respect to the parent node expanding. At first I was using a TreeWillExpandListener that fired off loading the children's children. I think I might can solve the white space in the tree problem by changing that to a TreeExpansionListener that uses the treeExpanded method. So far this seems to be working...so that the parent node is done expanding before the second thread begins loading the children's children.
    Any thoughts?

    I actually found the thread3 article first... since there doesn't seem to be direct links between them, I thought I would add for anyone who reads this thread that there are several related articles. sabre150 linked the first; the others are the same base URL but with the number incremented for each. For example, the 2nd article is:
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html]
    And the 3rd article, which most directly applies to what I am doing, is:
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html]
    Edited by: Skotty on Mar 5, 2009 9:35 PM -- links turned into actual links
    Edited by: Skotty on Mar 5, 2009 9:36 PM -- formatted for nicer display

  • About JTree display

    I built a JTree and I want to do some searching on the tree. How to find a node and display it on the screen. Do I need reload the data from database?
    THX

    Assuming you are using DefaultMutableTreeNode: just get the root node. There are several Enumerations you can use that allow you to examine every node in the tree below that node. (Check the API documentation for details.) Then compare the user object in each node with whatever you are looking for.

  • JTree: displaying something other than default toString

    Ahoy. I'm working on displaying the structure of some complex objects using a jtree. (Just displaying at the moment, not editing).
    I've chosen to do this at the moment by making the structure itself implement TreeModel, but I could just as well use a DefaultTreeModel.
    My structure contains Lists of other objects. Since I've overridden toString() in those objects, they display fine, but the list that contains them (and forms the parent node) displays the default toString of the ArrayList (or whatever), listing the contents in square brackets.
    The kludge I've done for now is to subclass ArrayList with my own "LabeledList" which takes a label in its constructor and returns it for toString(). This works, but isn't ideal.
    How am I supposed to do it? All I can find is "Sometimes, it is not feasible to override toString; in such a scenario you can override the convertValueToText of JTree to map the object from the model into a string that gets displayed." at http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/tree.html. This is in the JTree itself, not the model and I don't see how I can do this and keep the view separate from the model. Am I supposed to do something like this, in the JPanel or watever class:
    JTree tree = new JTree() {
      String convertValueToText(Object obj) {
        if(obj instanceof List<?>)
          //work out what I want to display somehow
        else
          super(obj);
    }That seems even worse than what I've already done. I'm kind of confused.

    Sounds like a job for a custom renderer. The JTree tutorial shows an example of one.

  • JCheckBox used in a JTree Displaying Wrong

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

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

  • Displaying a jtree with checkboxes and enabling some default checkboxes

    I have created a jtree displaying a list of nodes hierarchically ,and created a checkbox for each node as well.
    My problem is having created the jtree with checkboxes i need to have some of the nodes in the hierarchy checked by default on first launch of the gui.To do this i read a list of treepaths from a file and would want to traverse the tree and enable the node after finding it,which is what i am having issue with.
    Your solution would be appreciated as i am a newbie and having got this far, feel like i need some back up :)
    Thanks & Regards
    Shashi

    I have created a jtree displaying a list of nodes hierarchically ,and created a checkbox for each node as well.
    My problem is having created the jtree with checkboxes i need to have some of the nodes in the hierarchy checked by default on first launch of the gui.To do this i read a list of treepaths from a file and would want to traverse the tree and enable the node after finding it,which is what i am having issue with.
    Your solution would be appreciated as i am a newbie and having got this far, feel like i need some back up :)
    Thanks & Regards
    Shashi

Maybe you are looking for