Creating expanded JTree

Hii
I've created a JTree which is working well I did something:
        int i = 0;
        treeNode = new DefaultMutableTreeNode("My Computer");
        File roots[] = File.listRoots();
        for(File f : roots)
            childTree = new DefaultMutableTreeNode(f.getAbsolutePath().toString());
            treeNode.insert(childTree,i++);
        model = new DefaultTreeModel(treeNode,true);
        jTree1.setModel(model);This is returning a default model. Actually I'm having a specific path which'll expand when JTree 'll be made at the first time. could you else please tell me how can I pass that path so that, the JTree will open that path by default!!!
thanks
Dev

This will show the whole tree
private void showTheTree(){
    int c = tree.getRowCount();
    int i = 0;
    while(i <= c){
        tree.expandRow(i);
        i++;
        c = tree.getRowCount(); // as you expand, you get more
    }

Similar Messages

  • Expand jTree

    Hi,
    I have got question how to expand JTree. I am using netbeans IDE.
    I would like to save information about last visited position in tree and when I open this window again to expand it to last visited node(leaf).
    I have done someting like that:
    String hostName = getHostName();
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(hostName)
    DefaultTreeModel treeModel = new DefaultTreeModel(root);
    JTree jTree1 = new JTree();
    jTree1.setModel(treeModel);
    //I have create method to create jTree:
    public void setTree(TreePath path)
    DefaultMutableTreeNode newNode;
    //Here I call method to get all root folders. For root it will be all disks.
    File[] folderList = getFolders(...)
    for(File f: folderList)
    newNode = new DefaultMutableTreeNode(f);
    root.add(newNode);
    Ok. That's how it create jTree. This part of code works correct. I invoke this window with other (main) window. I have got treeNode e.g.
    [ TRAVEL, C:\, C:\Program Files ]
    I strange because I checked that on second level node has leaf but it doesn't handle and folder icon. I have tried jTree1.repaint but it doesn't work.
    How can I expand tree to this node. I have been trying:
    --scrollPathToVisible method
    When I select a node by mouse clicking then tree refreshes and show handle with folder icon and all leafs. I have selected the same node using setSelectionPath(treePath) but it is not working and trying to expand it but it is not working.
    Give me a sign if you need more information.
    Peter D.

    It only took me 20 seconds to do a search and find this, but since you've waited over five hours, here's one result I found
    http://forum.java.sun.com/thread.jsp?forum=31&thread=257313

  • How to create a JTree using a tree of my own

    Hello,
    I have an object which has a tree structure.
    I want to create a jtree that will hold the data from this tree of my own. I also want to be able to customize how nodes are rendered and to add a context menu with options like ADD/Remove/Move....
    Can you point me to a good tutorial?
    Can you help me?
    Thank you very much for your asistance.

    carstos,
    See this article for a not-extremely-well-written, but still useful, intro to trees:
    http://java.sun.com/products/jfc/tsc/articles/jtree/index.html
    After that see the Swing Tutorial at http://java.sun.com for specific help on popup menus, etc.
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How can create a JTree with cellRender is checkbox realized multiple selec

    How can create a JTree with cellRender is checkbox realized multiple selection function.thanks for every
    one's help.

    Hi,
    1. Create a value node in your context name Table and set its cardinality to 0:n
    2. Create 2 value attributes within the Table node name value1 and value2
    3. Goto Outline view> Right click on TransparentUIContainer>Apply Template> Select Table>mark the node Table and it's attributes.
    you have created a table and binded its value to context
    Table UI properties
    4.Set Selection Mode to Multi
    5.Set Visible Row Count to 5
    6.ScrollableColCount to 5
    In your implemetaion, you can add values to table as follow:
    IPrivate<viewname>.ITableElement ele = wdContext.nodeTable().createTableElement();
    ele.setValue1(<value>);
    ele.setValue2(<value>);
    wdContext.nodeTable().addElement(ele);
    The above code will allow you to add elements to your table node.
    Regards,
    Murtuza

  • Create expandable text boxes & maintain Indesign interactive features

    I have a form created in indesign which has interactive buttons included. I exported to pdf and now need to add expandable text boxes. I tried to do this in Livecycle but when i imported the pdf as a flowable form (with a view to make it dynamic) the interactive buttons i had created disappeared. is there a way around this so that i can create expandable text boxes but still maintain the buttons i have created?
    PS i am completely new to Livecycle

    Hi Reggie,
    Here are two versions. One form with a fixed number of pages and the other with a variable number of pages (you can add additional page 1).
    In the fixed number of pages, the click event of the index button includes the following instruction to go to a target page:
    xfa.host.currentPage = 1;
    This works because the page we want is always "1".
    If the form is dynamic and the number of pages can increase (or decrease) from those set at design, then we need to track the actual page number of each target page, at runtime.
    The script in the index button now looks like this:
    xfa.host.currentPage = page2.thisPage.rawValue - 1;
    Here the target page is page2 and on this page we have a field called "thisPage". The instruction is to jump to the current value of thisPage on page 2.
    For each target page that you want to index, you will need a hidden field (thisPage). You need to put this on each page and not on the Master Page.
    Hopefully the examples will help explain this.
    This is how we do it, there probably are other solutions out there.
    In relation to the second part, the link feature in Acrobat will not work with a form developed in LC Designer. Paul has a thread (http://forums.adobe.com/message/1923918#1923918) with a PDF for attaching documents, which were then listed in a list box. This could help you in developing your form.
    Another option is to have a button which becomes visible is there are attachments in the PDF. The click event then shows/hides the attachment panel. The user can then see the attachment and double click on the one they want/need. I know it is not as clean, but it is easier to implement. The javascript for the button would be:
    app.execMenuItem("ShowHideFileAttachment");
    Hope that helps,
    Niall
    the text keeps collapsing...

  • Using reflection to create a JTree representing an object

    I�m trying to implement a Java component which represents an Object tree.
    the idea is to receive a generic Object and then to create a JTree with all attributes of this object... If an attribute is a list or other complex object, than my component include subnodes into the tree with the contents of this collections, etc.
    my current first steps:
    private DefaultMutableTreeNode setAttributesTree(Object obj) {
         DefaultMutableTreeNode root = new DefaultMutableTreeNode(obj.toString());
         Class userObjectClass =obj.getClass();
         Field[] fields = userObjectClass.getDeclaredFields();
         for(int i=0; i<fields.length; i++) {
              try {
                   fields.setAccessible(true);
                   root.add(new DefaultMutableTreeNode(fields[i].getName() + " = " + fields[i].get(obj)));
              } catch (Exception e) {
                   System.out.println("some bug");

    interesting approach.. I wiil try that... bellow is my current code, which runs well to the first level of attributes.. When I tryied to load the deeper levels, it caused a StackOverflow... I will try the cited approach...
    /** 2003 � www.atlantico.com.br */
    package com.atlantico.sigweb.util;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.lang.reflect.Field;
    import java.util.Collection;
    import java.util.Iterator;
    * Esta classe re�ne funcionalidades que n�o est�o vinculadas
    * a um processo espec�fico.
    * @author Felipe Ga�cho
    * @version 15/09/2003
    public abstract class Util {
         * M�todo que recebe um objeto qualquer e retorna a ra�z
         * da �rvore de atributos deste objeto. Este m�todo usa
         * reflection para inspecionar o objeto recebido.
         * @param object O objeto a partir do qual a �rvore de
         * atributos ser� constru�da.
         * @return A �rvore de atributos.
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
        public static DefaultMutableTreeNode inspect(Object object)
            throws IllegalArgumentException, IllegalAccessException {
            if (object == null) {
                return null;
            DefaultMutableTreeNode root =
                new DefaultMutableTreeNode(object.toString());
            Class userObjectClass = object.getClass();
            Field[] fields = userObjectClass.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                fields.setAccessible(true);
    Object field = fields[i].get(object);
    DefaultMutableTreeNode child =
    new DefaultMutableTreeNode(fields[i].getName());
    inspect(child, fields[i]);
    ((DefaultMutableTreeNode) root).add(child);
    return root;
    public static void inspect(DefaultMutableTreeNode root, Object object)
    throws IllegalArgumentException, IllegalAccessException {
    if (object instanceof Collection) {
    for (
    Iterator children = ((Collection) object).iterator();
    children.hasNext();
    Object next = children.next();
    DefaultMutableTreeNode nextNode =
    new DefaultMutableTreeNode(next);
    inspect(nextNode, next);
    root.add(nextNode);
    } else {
    Class objectClass = object.getClass();
    Field[] fields = objectClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
    fields[i].setAccessible(true);
    Object field = fields[i].get(object);
    root.add(
    new DefaultMutableTreeNode(
    fields[i].getName() + " = " + fields[i].get(object)
    private static DefaultMutableTreeNode inspectR(Object object)
    throws IllegalArgumentException, IllegalAccessException {
    DefaultMutableTreeNode node =
    new DefaultMutableTreeNode(object.toString());
    Class objectClass = object.getClass();
    Field[] fields = objectClass.getDeclaredFields();
    if (fields.length > 0) {
    for (int i = 0; i < fields.length; i++) {
    fields[i].setAccessible(true);
    Object field = fields[i].get(object);
    node.add(inspectR(field));
    return node;

  • Creating tree (JTree) for showing directories/files

    Hi All,
    I need to create a JTree that show all files and directories in my computer. I know to create a simple tree, but I don't know how to access files...
    Does somebody know a code to do it?
    thanks,
    Inbal

    I know to create a simple
    tree, but I don't know how to access files...See java.io.File

  • Enter key not expanding JTree branches in 1.4?

    Hi,
    I have noticed that when pressing enter when a node is selected in a Jtree does not perform an expand/collapse on a branch or a programatic "double click" if it is a leaf. This seems to only apply to JDK 1.4. In 1.3 it does have this behaviour.
    Does this sound right?
    If for whatever reason this feature was removed, what is the workaround? I tried using a KeyListener and that did not seem to work.

    I have found a workaround. The following will allow the tree to expand/collapse branches on pressing "Enter".
    tree.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "toggle");where "tree" is an instance of JTree. (BTW, I disconvered this by making a comparison between the WindowsLookAndFeel class in 1.3 and 1.4.)
    However, I still cannot get it to do the programmatic equivelant of double clicking on a leaf. I am able to get a keylistener to listen for when [Enter] is pressed but I don't know where to go from there.
    Here is my code so far.
    * Created on Sep 9, 2003
    package Andar;
    import java.awt.event.*;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.KeyStroke;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * @author avromf
    public class TreeDemo extends JTree
         private DefaultMutableTreeNode currentNode;
         public static void main(String[] args)
              JFrame frame= new JFrame("Test");
              TreeDemo tree= new TreeDemo();
              frame.getContentPane().add(tree);
              frame.setSize(300,200);
              frame.setVisible(true);
         public TreeDemo()
              super();
              getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              addTreeSelectionListener(new TreeSelectionListener()
                   public void valueChanged(TreeSelectionEvent e)
                        currentNode = (DefaultMutableTreeNode) getLastSelectedPathComponent();
              getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "toggle");
              addKeyListener(new KeyAdapter()
                   public void keyTyped(KeyEvent e)
                        if (currentNode != null && currentNode.isLeaf() && e.getKeyChar() == '\n')
                             System.out.println(currentNode);                    
    }Any suggestions?

  • Creating Expandable fields in Abobe Acrobat 9.0 professional

    Hello,
    I am in the process of converting a standard PDF file to a interactive one. The problem I am having is that some of the fields need to be expandable to accommodate needs of the application. I am using Adobe Acrobat 9.0 to convert the standard form into a PDF file to PDF interactive file.
    I have looked in Adobe Acrobat 9.0 Professional but I have not been able to find any documentation on how to expand the fields in the 9.0 Professional version.
      Can you tell me if the LiveCycle Designer has the ability to expand fields and if so how can I set up the document to create the expanded fields. I have reviewed the help documents but it not very clear as to how to go about accomplishing this task.
    I have attache the form that I like to expand.
    I would really appreciate some guidance in this area
    Thank you for your time
    Gary

    Hi,
    Yes, LC has expandaple fields.
    First you have to make your field multiline
    Second - make it expand:
    But you shaould remember tha field will be expanded only after you type smth in it and lost focus.
    BR,
    Paul Butenko

  • Is it possible to create expandable fields in an interactive PDF? (not dropdown menus)

    Need to design an interactive PDF that has expandable fields for respondents to include more that one group of answers. Specifically, they will be asked to list all previous employment. Some respondents may have had 10 relevant positions. The form will get too long if I create fields for 10 responses. Hoping to find a way that fields will expand if a respondent needs them.

    Not really possible with PDF forms, unless you create an entire page
    dedicated to this and allow the user to spawn new copies of it as needed.
    On Thu, Mar 5, 2015 at 9:06 PM, deborahs98069952 <[email protected]>

  • Creating expandable panels in LiveCycle

    I am in the middle of creating a dynamic pdf for my customers. I am offering various products and the information I need from my customers varies for every product. However, I would like to have only 1 pdf form that I can send to every customer and within the form, the customer can choose which product he purchased. The pdf should then "adapt" to the customers choice and show the important forms to be filled.
    Here´s a quick example: At the beginning of the document, the customer gives his details like name adress etc. This information is neccessary no matter what the product is, but there´s some information that´s only neccesary for certain products. Is it possible to create buttons (i.e. "choose your product") and link them to panels which will then pop up when the corresponding button is clicked?
    The only function I´ve found is the expandable text form, but I need whole "panels" to be hidden/visible.
    Thanks in advance

    Thank you, this is what I was looking for. Now I´ve come across another problem: I´ve placed my forms over eachother so that there´s no gap on the page if somebody checks option 2 instead of option 1. Is there a way to automatically place one form below the other if both options are checked? Best wishes

  • An Expandable JTree Problem

    Hi, I'm relatively new to creating JTree components, now I have looked at many examples, and this one is nearest (i can see) to how I want my Jtree to look, however it doesn't behave in a way which I would like!
    Firstly, I can set the root node to have as many folders as i want, however they only mirror whats in the first root node, I dont want this - I want to be able to create about 5/6 different roots that will yield different results - I also want after each time you click on a folder, which will ask a question about a patient i.e. "Has the patient a head injury" - click on this then it should come up with "3" more different choices, so altogther want it about 5 deep.
    However, this is what I've got so far - but like I say, its not yielding the results I want, does anyone know how to modify this or can anyone point me in the right direction by starting me off a bit, that would be great!
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class SelectableTree extends JFrame
                                implements TreeSelectionListener {
      public static void main(String[] args) {
        new SelectableTree();
      private JTree tree;
      private JTextField currentSelectionField;
      public SelectableTree() {
        super("Clinical Information Help System");
        WindowUtilities.setNativeLookAndFeel();
        addWindowListener(new ExitListener());
        Container content = getContentPane();
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Begin Clinical Questions");
        DefaultMutableTreeNode child = null;
        DefaultMutableTreeNode parent = null;
        DefaultMutableTreeNode grandChild = null;
        DefaultMutableTreeNode grandParent = null;
        DefaultMutableTreeNode child2 = null;
        DefaultMutableTreeNode parents = null;
        for(int grandParentIndex=1; grandParentIndex < 2; grandParentIndex++) {
          grandParent = new DefaultMutableTreeNode("[Does Patient Have Back Pains?] " + grandParentIndex);
          root.add(grandParent);
          for(int parentIndex =1; parentIndex < 3; parentIndex++) {
            parent = new DefaultMutableTreeNode("[Does the patient also have leg pain?] " + parentIndex +
                                         "." + parentIndex);
            grandParent.add(parent);
            for(int childIndex =1; childIndex < 3; childIndex++) {
             child = new DefaultMutableTreeNode("[are the pains in the lower back?] " + childIndex +
                                         "." + childIndex);
              parent.add(child);
              child2 = new DefaultMutableTreeNode("patient over 60?" + childIndex +
                    "." + childIndex);
              child.add(child2);
            for(int grandChildIndex =1; grandChildIndex < 3; grandChildIndex++) {
               grandChild = new DefaultMutableTreeNode("[Does patient have bladder and/or bowel incontinence?] " + grandChildIndex +
                                            "." + grandChildIndex);
                 child.add(grandChild);
            for(int childIndex = 1; childIndex < 3; childIndex++) {
                child = new DefaultMutableTreeNode("[Has Patient suffered either: appitite/wieght loss/fever?]" + childIndex +
                                             "." + childIndex);
                child = new DefaultMutableTreeNode("[Has pain been 4-6wks leg pain? OR 3-6mths low-back pain?]" + childIndex +
                        "." + childIndex);
                  grandChild.add(child);
        tree = new JTree(root);
        //tree = new JTree(root2);
        tree.addTreeSelectionListener(this);
        content.add(new JScrollPane(tree), BorderLayout.CENTER);
        currentSelectionField = new JTextField("Current Selection: NONE");
        content.add(currentSelectionField, BorderLayout.SOUTH);
        setSize(400, 400);
        setVisible(true);
      public void valueChanged(TreeSelectionEvent event) {
        currentSelectionField.setText
          ("Current Selection: " +
           tree.getLastSelectedPathComponent().toString());
    }

    I'm not really sure what your problem is, for I don't see what you mean by "mirror". If it is you have but one root node, but wanted to have many instead, then you'd simply need to call setRootVisible(false); on the tree.
    As a sidenote, I don't think it's a really good UI for what you're doing, but after all, I haven't got the whole picture.
    Now, what is it you mean by: its not yielding the results I want ?

  • How to create a JTree in which only leafs are selectable

    It took me a while and some effort to find a way to make a JTree in which you can only select the leafs.
    I'm posting the example in case someone is interested. This might be helpful.
    myJTree.setSelectionModel(new DefaultTreeSelectionModel() {
         public void setSelectionPaths(final TreePath[] paths) {
              boolean okToAdd = true;
              DefaultMutableTreeNode selectedNode;
              for (int i = 0; i < paths.length; ++i) {
                   selectedNode=(DefaultMutableTreeNode)paths.getLastPathComponent();
                   if (!selectedNode.isLeaf()) {
                        okToAdd = false;
                        break;
              if (okToAdd) {
                   super.setSelectionPaths(paths);
         public void addSelectionPaths(final TreePath[] paths) {
              if (getLeadSelectionPath() == null) {
                   super.addSelectionPaths(paths);
                   return;
              boolean okToAdd = true;
              DefaultMutableTreeNode selectedNode;
              for (int i = 0; i < paths.length; ++i) {
                   selectedNode=(DefaultMutableTreeNode)paths[i].getLastPathComponent();
                   if (!selectedNode.isLeaf()) {
                        okToAdd = false;
                        break;
              if (okToAdd) {
                   super.addSelectionPaths(paths);

    For this to work in PDF the client ither needs Acrobat Pro or you need to create a PDF form (which has it's disadvantages concerning design)
    In any way PDF is not actually meant for editing. The editing functions in Acrobat have their disadvantages as well if carefully set type is what you're after.
    A vector file simply can't be protected.
    Make a contract.

  • How to create a JTree in a separate thread?

    Hi. I am writing a Swing application which has a JTree that is made up of company parent nodes and employee child nodes. My problem is that the data for this JTree is loaded from the database and this process takes a long time making the loading time of the app too slow. I think that this process should probably be done in a separate thread. This would let the gui load much quicker and then when the thread finishes it can update the graphics to display the JTree. I have the code for the JTree all done and it works but I need help on putting it in a separate thread and running the thread. I am having trouble with this. Any help would be greatly appreciated.
    Eugene P.

    Thank you for responding to my question but I actually figured out a solution already. I used the SwingWorker class. When the program loads I just display a simple JTree with just the names of the companies without the employees. This takes almost no time to load. Then in the construct() method of the SwingWorker class I run the query to get the employee names and then create the new JTree that has the firms and the employees. In the finished() method of the SwingWorker class I update the gui. This whole process is running in a separate thread while the gui is already loaded so it works beautifully.

  • Creating Dynamic JTree

    Hi everybody,
    I'm interested in creating GUI using JTree to display a records that read from the database.
    The previous-button and next-button is used to display previous and next records on the same JTree (Dynamic Tree). 20 different records will be displayed in the tree each time both buttons is clicked.
    When the node on the jtree is clicked the details of the record will be displayed onto other component may be textarea.
    How should I do that. Dynamic Tree?
    Any Help. Thanks you.

    I want to ...
    ... display them using a JTree....
    ... Do I need to use a JTree ? ...of course you do need a JTree if you want to display a JTree =0
    you would add/remove your users to the tree as nodes, check out http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    thomas

Maybe you are looking for

  • How do I set up a page that a user can edit online?

    I am setting up a simple website for a restaurant moxibistro.com. The client has asked me to set up a page for her "Weekly Special" She wants to be able to edit this page once a week with a different special. She doesn't have a mac so I'm thinking th

  • Error while accesing Bex web analyzer from business planning

    Hi all, we   are using portal  7  sp 15   and   bi 7  sp 17  . we are able to view  planning modeller  and planning  wizard through portal . but while accessing  bex web analyzer  it is giving following error #1.5 #000BCD3C982F005C000001B600000BF8000

  • Date / Time In SAP ... is it the server Date / Time ?

    Hi, If my understanding is all right, the date/time in SBO application is the date/time on the server... If I have many offices in the world and they wish to manage BP activities... Does that mean that the reminders will come up when the SERVER will

  • Salutation in mail forms.

    Dear CRM gurus. We are facing the following issue. When we want to create a mail form and when we want to create text different text elements using different salutation, we cannot use the conditions properly. We cannot use basic conditions  for disti

  • Links in database

    I am trying to find out if it is possible to set up links in database (Appleworks 6), and if so, how. Right now, the links screen pops up, but won't actually let me do anything. Any suggestions?