• RELEVANCY SCORE 4.49

    DB:4.49:Jtree pp





    how can i get The selected Node s name of a JTree???

    DB:4.49:Jtree pp

    Not sure what you want but is this helpful?

    JTree tree= new JTree();
    Object o = tree.getLastSelectedPathComponent();
    String s = o.toString();Hamed

    Message was edited by:
    Hamed

  • RELEVANCY SCORE 3.54

    DB:3.54:Get Jtree Node's Name? Urgent !!!!! cc





    DefaultMutableTreeNode node1=new DefaultMutableTreeNode("A");

    I can get node's user object.like this :

    TreePath path = tree.getSelectionPath();
    DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)path.getLastPathComponent();
    currentNode.getUserObject()//get node's user object "A"

    How can I get JTree Node's name "node1" ?
    I mean get DefaultMutableTreeNode("A") 's name "node1".
    what's the method?

    DB:3.54:Get Jtree Node's Name? Urgent !!!!! cc

    create an own UserObject that contains the name and the url.

    class TreeLink {
    String name;
    String url;
    public TreeLink(String name, String url) {
    this.name = name;
    this.url = url;
    }

    public void toString() { return name;}

    public String getURL() { return url;}
    }

    initialize your treenodes with TreeLink instances, e.g.
    node[2] = new DefaultMutableTreeNode(new TreeLink("A", "fkk") );

    add a TreeSelectionListener to the tree.
    get the clicked node from the TreePath passed to the Listener, when a node is clicked.
    now you can get the TreeLink Object and the url from the node (its a lot of casting though).

    regards,
    stefan

  • RELEVANCY SCORE 3.42

    DB:3.42:Problem, Insert Node Into Jtree At Runtime. Urgent x3





    Hello there,
    Below code adds jtree with root node as "Groups", under that "Default Groups", "User Groups" are sub nodes.

    i.e.,...
    * Groups
    - Default Groups
    @ Friends
    @ Family
    @ Co-Workers
    - User Groups

    There are two buttons that allow user to "create new group" and "cancel".
    when user click on create new group, an OptionPane.showInputDialog is displayed to get input(i.e., new group name) from user and this should be added at selected path.

    //-----------------------------------------------------
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;

    public class Groups extends JDialog implements ActionListener {
    JScrollPane jsp;
    JButton jButton1 = new JButton();
    JButton jButton2 = new JButton();

    DefaultMutableTreeNode ngp=new DefaultMutableTreeNode("Groups");
    DefaultMutableTreeNode n0=new DefaultMutableTreeNode("Default Groups");
    DefaultMutableTreeNode n1=new DefaultMutableTreeNode("Friends");
    DefaultMutableTreeNode n7=new DefaultMutableTreeNode("Family");
    DefaultMutableTreeNode n13=new DefaultMutableTreeNode("Co-Workers");
    DefaultMutableTreeNode n00=new DefaultMutableTreeNode("User Groups");

    DefaultMutableTreeNode inode;
    JTree jtr;

    public Groups() {
    try {
    jbInit();
    }
    catch(Exception e) {
    e.printStackTrace();
    }
    }

    private void jbInit() throws Exception {
    this.getContentPane().setLayout(new BorderLayout());
    setModal(true);

    JPanel p1=new JPanel();
    jButton1.setFont(new java.awt.Font("Monospaced", 0, 14));
    jButton1.setBorder(BorderFactory.createRaisedBevelBorder());
    jButton1.setText("Create New Group");
    jButton1.addActionListener(this);
    jButton1.setBounds(new Rectangle(36, 183, 149, 48));
    jButton2.setFont(new java.awt.Font("Monospaced", 0, 14));
    jButton2.setBorder(BorderFactory.createRaisedBevelBorder());
    jButton2.setText("Cancel");
    jButton2.setBounds(new Rectangle(222, 183, 94, 48));
    jButton2.addActionListener(new cancel());
    p1.add(jButton1);
    p1.add(jButton2);

    n0.add(n1);
    n0.add(n7);
    n0.add(n13);
    ngp.add(n0);
    ngp.add(n00);

    jtr=new JTree(ngp);

    int v=JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h=JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    jsp=new JScrollPane(jtr,v,h);
    jtr.setBounds(new Rectangle(40, 24, 276, 130));
    jtr.setBorder(BorderFactory.createRaisedBevelBorder());
    this.getContentPane().add(jsp);
    this.getContentPane().add(p1,BorderLayout.SOUTH);

    }

    public void actionPerformed(ActionEvent e)
    {
    String s=JOptionPane.showInputDialog(this,"Enter new Group name ");
    System.out.println(s);
    inode=new DefaultMutableTreeNode(s);
    ngp.add(inode);
    jtr.addSelectionRow(5);
    System.out.println("end");
    }

    public class cancel implements ActionListener
    {
    public void actionPerformed(ActionEvent e)
    {
    dispose();
    }
    }

    public static void main(String a[])
    {
    Groups gp=new Groups();
    gp.setTitle("Groups");
    gp.setSize(350,290);
    gp.setVisible(true);
    }
    }

    //-----------------------------------------------------

    Does anyone know code for this...URGENT..
    Any help will be highly appreciated
    Sangeetha.
    ~~~~~~~~~~

    DB:3.42:Problem, Insert Node Into Jtree At Runtime. Urgent x3

    some modification could solve your problem

    1. Declaration

    DefaultTreeModel treemodel;

    2. build your jtree

    treemodel = new DefaultTreeModel(ngp);
    jtr=new JTree(treemodel);

    3. after inserting new node

    treemodel.reload((DefaultMutableTreeNode)jtr.getLastSelectedPathComponent());

  • RELEVANCY SCORE 3.42

    DB:3.42:How To Find Treepath From A Node In Jtree-Urgent fs


    i want to use expandPath(treepath) method in my application which takes treepath as input parameter. So, how to get TreePath from a node. From a node.getPath() i'm getting treeNode array. Is it possible to get treepath from that treenode array.
    thanks in advance for suggestions.

  • RELEVANCY SCORE 3.38

    DB:3.38:How To Get The Children For A Selected Tree Node? az


    Hi,

    I want to get the number of child nodes for any selected node in JTree.
    How can i do this?

    Any help, greatly appreciated!!

    DB:3.38:How To Get The Children For A Selected Tree Node? az

    Try to use something like this

    JTree tree;

    TreePath path=tree.getSelectionPath();
    TreeNode selectedNode=(TreeNode)path.getLastPathComponent();
    int count=selectedNode.getChildCount();

    best regards
    Stas

  • RELEVANCY SCORE 3.24

    DB:3.24:Get Node Jtree Without Click j8


    hi all,

    I want get node from jtree without click, just with mouse in node.

    I look in google but dont find nothing...

    I try use listener but MousePressed dont help-me.

    thanks

    DB:3.24:Get Node Jtree Without Click j8

    jTree1 = new JTree1(treeModel);Sorry, now

    jTree1 = new JTree(treeModel);
    MouseMotionListener mm = new MouseMotionListener(){
    public void mouseMoved(MouseEvent e) {

    System.out.println("moved "+e.getX()+" "+e.getY());
    int selRow = jTree1.getRowForLocation(e.getX(), e.getY());

    TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());


    if(selRow != -1) {
    System.out.println("mouse moved..."+selPath);
    }
    }

    public void mouseDragged(MouseEvent e) {
    System.out.println("dragged "+e.getX()+" "+e.getY());
    }
    };

    jTree1.addMouseMotionListener(mm);
    jScrollPane1.setViewportView(jTree1);

  • RELEVANCY SCORE 3.22

    DB:3.22:Jtree Display Update ak


    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; icardArray.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.

  • RELEVANCY SCORE 3.19

    DB:3.19:Select Specified Node In Jtree j7


    I am very appreciated if anyone could help me in selecting the specified node in JTree by code
    I tried the code below:
    jTree.setSelectionPath(treePath);But how we can get path of the node???

    By the way, Can we customize JTree acting like the hyper link? (change color when mouse over)

    DB:3.19:Select Specified Node In Jtree j7

    I am very appreciated if anyone could help me in selecting the specified node in JTree by code
    I tried the code below:
    jTree.setSelectionPath(treePath);But how we can get path of the node???

    By the way, Can we customize JTree acting like the hyper link? (change color when mouse over)

  • RELEVANCY SCORE 3.15

    DB:3.15:Collapsing A Jtree Node? k7


    hi, i am trying to collapse a jtree node including all chlidren. here is what i have:

    //tpath is a treepath from the node i want to collapse
    //tpath works, i have tested this
    Enumeration en = t.getExpandedDescendants(tpath);
    TreePath test=null;
    for (;en.hasMoreElements();) {

    String s = en.nextElement().toString();

    s=s.replaceAll("^\\[", "");
    s=s.replaceAll("\\]$", "");

    test = new TreePath(s);
    System.out.println("collapsing: " + test);
    t.collapsePath(test);
    }the node wont collapse:-( any ideas?

    THANKS A LOT!!

    DB:3.15:Collapsing A Jtree Node? k7

    Seems you are getting your TreePath messed

    public TreePath(Object singlePath)
    Constructs a TreePath containing only a single element. This is usually used to construct a TreePath for the the root of the TreeModel. - from J2SDK API Reference

    Denis Krukovsky
    http://sourceforge.net/projects/dotuseful/

  • RELEVANCY SCORE 3.12

    DB:3.12:Jtree Question Urgent za


    Hi,

    I am working on a Swing Project.
    In wich i have a control Tree, for which i used JTree class.
    The Tree Structure looks as below.

    Root
    Element1
    Sub1
    Sub2
    Sub3
    Element2
    Sub4
    Sub5
    Sub6

    Now my Question is, if I double click on a node sub4, I have to get an output on the screen that as "sub4".
    I need to put the below statement, so that i can get "sub4" as output......
    System.out.println(selected node);

    Regards,
    Ravi Kumar Garlapati

    Message was edited by:
    rkrgarlapati

    DB:3.12:Jtree Question Urgent za

    Torgil,

    I am extremly sorry for my word.....actually i am new to swing technology.
    This question consumed lot of time.....so i thougt of putting this question in forum.

    Regards,
    Ravi Kumar Garlapati

  • RELEVANCY SCORE 3.10

    DB:3.10:Urgent: Jtree Distored On Adding The Nodes By Thread dx


    Hi all,

    I have a JTree with more number of nodes. The Jtree is having Drag and drop functionality.

    Suppose there exists a structure as follows:

    A
    A.B
    A.B.C
    A.D

    where A is the root node. B is a folder node and C and D are leaf nodes.

    List this the Tree has lots of nodes in it.

    When I drag and drop 'C' to 'A', which is being threaded, the JTree gets distorted at the time of dropping. And after the drop completes, the JTree gets the original structure.

    This distortion doesn't take place if the dropping is not threaded.

    Here is the code snippet which is called when node structure is changed.

    public void nodeStructureChanged(TreeNode node) {
    try {
    ((SDLTreeNode) node).reload();
    }
    catch(RemoteException e) {
    throw new RuntimeException("Error occured reloading node " + node + ": " + e.getMessage());
    }
    super.nodeStructureChanged(node);
    }

    Any sugessions or help in this regard is more welcome

    Regards,
    S. Seetha Raman

    DB:3.10:Urgent: Jtree Distored On Adding The Nodes By Thread dx

    Yes. But I couldnt get the solution from there.

    Urgent help required.

  • RELEVANCY SCORE 3.09

    DB:3.09:Urgent - Table Rendering In A Jtree sp


    Hi Guys/Gals

    I am try to design something like this:

    http://www.mutualinstrument.com/Easy/Products/In_mind/tbl_tree.gif

    Here is my source code for the tree:

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.event.*;
    import java.lang.*;

    public class SimpleTree extends JFrame {
    public static void main(String[] args) {
    new SimpleTree();
    }

    public SimpleTree() {
    super("Creating a Simple JTree");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());

    Container content = getContentPane();

    // ---------- CREATE TABLE HERE --------------------------------

    JTabletable;
    String columnNames[] = { "OrderID", "CustomerID", "EmployeeID", "Order Date", "Shipped Date" };
    // Create some data
    String dataValues[][] =
    {
    { "12", "234", "67","12/02/2002", "16/04/2002" },
    { "-123", "43", "853","12/02/2002", "16/04/2002" },
    { "93", "89.2", "109","12/02/2002", "16/04/2002" },
    { "279", "9033", "3092","12/02/2002", "16/04/2002" }
    };

    // Create a new table instance
    table = new JTable( dataValues, columnNames );

    // ------------------------------------------------------------

    Object[] hierarchy =
    { "Orders",
    table,
    new Object[] { "Orders",
    "Order Number"},
    new Object[] { "Prodcuts",
    new Object[] { "Customers",
    "Customer Name" },
    },
    "Employees",
    "Suppliers" };

    DefaultMutableTreeNode root = processHierarchy(hierarchy);
    JTree tree = new JTree(root);

    tree.setCellRenderer(new MyTreeCellRenderer(table));

    content.add(new JScrollPane(tree), BorderLayout.CENTER);

    setSize(275, 300);
    setVisible(true);
    }

    /** Small routine that will make node out of the first entry
    * in the array, then make nodes out of subsequent entries
    * and make them child nodes of the first one. The process is
    * repeated recursively for entries that are arrays.
    */

    private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
    DefaultMutableTreeNode node =
    new DefaultMutableTreeNode(hierarchy[0]);
    DefaultMutableTreeNode child;
    for(int i=1; ihierarchy.length; i++) {
    Object nodeSpecifier = hierarchy;
    if (nodeSpecifier instanceof Object[]) // Ie node with children
    child = processHierarchy((Object[])nodeSpecifier);
    else
    child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
    node.add(child);
    }
    return(node);
    }
    }

    and here is the code for the tree cell renderer:

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.event.*;
    import java.lang.*;

    public class MyTreeCellRenderer extends DefaultTreeCellRenderer
    {

    JTable table = null;
    public MyTreeCellRenderer( JTable table)
    {
    super();
    this.table = table;
    updateUI();
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value,boolean selected, boolean expanded,boolean leaf, int row,boolean hasFocus)
    {
    super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

    if ( leaf )
    {
    Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
    if ( userObject instanceof JPanel ) {
    JPanel pnlLeaf = (JPanel)userObject; tree.setRowHeight(-1);
    // set u'r panel dimensions here pnlLeaf.setPreferr29/08/2002edSize(new Dimension( table.getWidth(), table.height() ));
    pnlLeaf.repaint();
    pnlLeaf.invalidate();
    pnlLeaf.validate();
    return pnlLeaf;
    }
    }

    return this;
    }
    }

    When I run this I dont get the table.....

    I get:

    javax.swing.JTable[0,0,0x0,invalid,alignment..........

    where the table is supposed to be displayed. I dont think it is getting rendered correctly. Any ideas??

    DB:3.09:Urgent - Table Rendering In A Jtree sp

    i tried to compile ur codes on

    SimpleTree.java
    TestCellEditor.java
    MyTreeCellRenderer.java

    but the result is a "stack over flow error"

    r u sure ur codes runs perfectly

    can u pls. list ur working codes

  • RELEVANCY SCORE 3.08

    DB:3.08:Urgent : Jtable As A Node Or Leaf Of A Jtree xx


    I am building an application that displays hierarchical set of data. So I thought of using JTree to display data and JTable to contain the columns and rows from the database tables. Does anyone know how to add a JTable as a Node for a JTree?

    Thanks!

    DB:3.08:Urgent : Jtable As A Node Or Leaf Of A Jtree xx

    I am building an application that displays hierarchical set of data. So I thought of using JTree to display data and JTable to contain the columns and rows from the database tables. Does anyone know how to add a JTable as a Node for a JTree?

    Thanks!

  • RELEVANCY SCORE 3.06

    DB:3.06:Interaction Between Jtree And List ax


    I have JTree and List on my application.
    when i select an item in list the appropriate node
    in jtree should get selected or getfocus

    DB:3.06:Interaction Between Jtree And List ax

    I have JTree and List on my application.
    when i select an item in list the appropriate node
    in jtree should get selected or getfocus

  • RELEVANCY SCORE 3.04

    DB:3.04:Jtree Usage fp



    Hi,

    In a tree I can get the current selected node
    (
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) trLocatari.getLastSelectedPathComponent();
    )
    but how can I get the parent as a DefaultMutableTreeNode ?
    I have only
    TreeNode parent = node.getParent ();

    regards,
    Lucian

    DB:3.04:Jtree Usage fp

    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
    trLocatari.getLastSelectedPathComponent();
    DefaultMutableTreeNode parent =
    (DefaultMutableTreeNode )node.getParent ();Huh? Didn't I post exactly that?!

  • RELEVANCY SCORE 3.02

    DB:3.02:Listeners Among Multiple Containers? am


    Hi-

    I'm trying to figure out how to get a listener from one container to affect an object in a different one. For example, my container heirarchy is :

    Applet
    JSplitPane
    Left: navigation bar
    Right: JTree

    The JTree is a separate class, with its own inner class containing a listener. My question is how to get the JTree 's listener - when a leaf node is selected, for example- to change the content of the navigation bar, for example.

    Thanks

    Michael Cantor

    DB:3.02:Listeners Among Multiple Containers? am

    Hi-

    I'm trying to figure out how to get a listener from one container to affect an object in a different one. For example, my container heirarchy is :

    Applet
    JSplitPane
    Left: navigation bar
    Right: JTree

    The JTree is a separate class, with its own inner class containing a listener. My question is how to get the JTree 's listener - when a leaf node is selected, for example- to change the content of the navigation bar, for example.

    Thanks

    Michael Cantor

  • RELEVANCY SCORE 3.02

    DB:3.02:Selecting A Node In Jtree 9f


    Hi,
    I am using JTree to show some information. I selected a node and added another item under it by using some mechanism(dialog based). Now when I update the JTree the whole JTree collapses(it shows only the root). How do I reset the state as before and reselect the node that I was initialy.
    Any urgent help is highly appreciated.
    Thanks
    asriva

    DB:3.02:Selecting A Node In Jtree 9f

    Thanks for replying but the does'nt work.
    -asriva

  • RELEVANCY SCORE 3.01

    DB:3.01:Urgent!!! Rename Node In Jtree zp


    I have a JTree constructed with a node called 'mynode' under a rootnode.
    If I take a String from user as 'MYNODE' from JTextField then how do I rename 'mynode' to 'MYNODE' ?

    Thanks

  • RELEVANCY SCORE 3.01

    DB:3.01:Access Data In A Jtree - Selection Path Of A Jtree 8j


    I've loaded a JTree with nodes from an XML Schema file using the XSOM API (https://xsom.dev.java.net).

    Every time a file is selected I do the folowing:

    schemaParser = new XSDParser(selectedFile.getAbsolutePath());

    TreeModel model = schemaParser.generateTreeModel();
    schemaTree.setModel(model);
    schemaTree.setCellRenderer(new SchemaTreeTraverser.SchemaTreeCellRenderer());schemaTree is the variable name for the JTree.

    The code for XSDParser is as follows:

    package schemaparser;

    import java.io.*;
    import com.sun.xml.xsom.XSSchemaSet;
    import com.sun.xml.xsom.impl.util.SchemaTreeTraverser;
    import com.sun.xml.xsom.impl.util.SchemaWriter;
    import com.sun.xml.xsom.parser.XSOMParser;

    import javax.swing.tree.TreeModel;

    public class XSDParser {

    private XSOMParser reader;
    private XSSchemaSet xss;

    public XSDParser(String parseFile){
    try {
    reader = new XSOMParser();
    reader.parse(new File(parseFile));

    xss = reader.getResult();
    if (xss == null) {
    System.out.println("error");
    }

    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }

    public TreeModel generateTreeModel() {
    SchemaTreeTraverser stt = new SchemaTreeTraverser();
    stt.visit(xss);
    TreeModel model = stt.getModel();

    System.out.println("Returning the tree model");
    return model;
    }
    }Now whenever a node is selected in the JTree I do the following:

    private void schemaTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {

    TreePath path = schemaTree.getSelectionPath();

    if(path != null)
    System.out.println(path.toString());

    }However now no matter which node I select in the tree I get something like: *[null, null, null, null]* (depending on how far the hierarchy I go)

    For a simple JTree this would usually print out the path to the node, e.g.: *[JTree, colors, red]*

    Anyone any idea how to fix this?

    Thanks,
    Patrick

    DB:3.01:Access Data In A Jtree - Selection Path Of A Jtree 8j

    I've loaded a JTree with nodes from an XML Schema file using the XSOM API (https://xsom.dev.java.net).

    Every time a file is selected I do the folowing:

    schemaParser = new XSDParser(selectedFile.getAbsolutePath());

    TreeModel model = schemaParser.generateTreeModel();
    schemaTree.setModel(model);
    schemaTree.setCellRenderer(new SchemaTreeTraverser.SchemaTreeCellRenderer());schemaTree is the variable name for the JTree.

    The code for XSDParser is as follows:

    package schemaparser;

    import java.io.*;
    import com.sun.xml.xsom.XSSchemaSet;
    import com.sun.xml.xsom.impl.util.SchemaTreeTraverser;
    import com.sun.xml.xsom.impl.util.SchemaWriter;
    import com.sun.xml.xsom.parser.XSOMParser;

    import javax.swing.tree.TreeModel;

    public class XSDParser {

    private XSOMParser reader;
    private XSSchemaSet xss;

    public XSDParser(String parseFile){
    try {
    reader = new XSOMParser();
    reader.parse(new File(parseFile));

    xss = reader.getResult();
    if (xss == null) {
    System.out.println("error");
    }

    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }

    public TreeModel generateTreeModel() {
    SchemaTreeTraverser stt = new SchemaTreeTraverser();
    stt.visit(xss);
    TreeModel model = stt.getModel();

    System.out.println("Returning the tree model");
    return model;
    }
    }Now whenever a node is selected in the JTree I do the following:

    private void schemaTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {

    TreePath path = schemaTree.getSelectionPath();

    if(path != null)
    System.out.println(path.toString());

    }However now no matter which node I select in the tree I get something like: *[null, null, null, null]* (depending on how far the hierarchy I go)

    For a simple JTree this would usually print out the path to the node, e.g.: *[JTree, colors, red]*

    Anyone any idea how to fix this?

    Thanks,
    Patrick

  • RELEVANCY SCORE 3.01

    DB:3.01:Urgent Anybody Pls Help Problem: Jtree ak


    Hai all
    I want to save the structure of a JTree. i.e if i have a tree structure as

    level1
    .... level2
    .....level2
    level1
    Now I dynamically add a new node to tree. Then it collapses as

    level1

    But what i want is to maintain its structure with out collapsing i.e after adding node it should be like this

    level1
    .... level2
    .....level2
    ......level2
    level1

    How can I do this ?

    Thanks in advance

    pradeep

    DB:3.01:Urgent Anybody Pls Help Problem: Jtree ak

    1) Swing questions should be posted in the Swing forum.

    2) Your postings are not "urgent".

    3) You still haven't replied to any of you previous postings to comment on the advice given. Instead you are cluttering the forum by posting new messages all the time.

  • RELEVANCY SCORE 2.99

    DB:2.99:Help Needed With Finding Node In Jtree xj


    Hi,

    In my application i will be entering some string data in a text box for search criteria.
    When I click on search, I will get data from database which will be shown as a JTree.
    This Jtree will have some nodes in which, node with string entered in the search text box exists.
    I need to focus on this node and I have only a string to find this node.
    How can I do this?How can I find a node in JTree using string value?
    Is there any alternate option by which I can achive my need?
    Please suggest.

    Thanks.

    DB:2.99:Help Needed With Finding Node In Jtree xj

    @OP: please assign your dukes.
    @Andre_Uhres: if you don't get rewarded in the next couple of days, please let me know here to get at least one duke for your effort.

    Bye.

  • RELEVANCY SCORE 2.99

    DB:2.99:Easy Jtree Question 7p


    I'm using something like the code below to "select" a node in my JTree. The node does get selected (an action is taken via the listener), however the node does not get selected in the graphical sense (i.e. the mouse selected node remains highlighted). How do I get the JTree to render the programatically selected node as the new selection?
    ...
    jTree.setExpandsSelectedPaths(true);
    jTree.setSelectionPath(jTreePath);
    ...Thanks

    DB:2.99:Easy Jtree Question 7p

    I'm using something like the code below to "select" a node in my JTree. The node does get selected (an action is taken via the listener), however the node does not get selected in the graphical sense (i.e. the mouse selected node remains highlighted). How do I get the JTree to render the programatically selected node as the new selection?
    ...
    jTree.setExpandsSelectedPaths(true);
    jTree.setSelectionPath(jTreePath);
    ...Thanks

  • RELEVANCY SCORE 2.98

    DB:2.98:Jtree: How To Get The Currently Selected Node dm


    How do I get the currently selected node in JTree?

    getLastSelectedPathComponent() this method always return the last selected node and not the current one.

    Thanks in advance
    Sachin

    DB:2.98:Jtree: How To Get The Currently Selected Node dm

    It sounds as if you're asking for a way to remember the one that was selected before the current node. If so, there's no API call for that. You'll have to remember it yourself. The most recent post provides a solution for getting the currently selected node (assuming only single selections), which works well in my application.

  • RELEVANCY SCORE 2.98

    DB:2.98:Jtree as


    a) What do i do to have JTree expanded and a particular node selected when the JTree comes up ?

    DB:2.98:Jtree as

    Hi,

    You can use JTree's expandPath(TreePath ...) method to expand a node.

    You can use setSelectionPath(TreePath...) method to select a node.

    Regards,
    Matt

    Java Developer Technical Support
    Sun Microsystems

  • RELEVANCY SCORE 2.98

    DB:2.98:Jtree jp


    Hello,

    I have a JTree it's binded to data from the database with a model. The model display the name.

    How can i get the id of the selected node ?

    DB:2.98:Jtree jp

    Yep, that's what I had in mind. I think you should write a utility method which performs this action in a 'generic' manner and will work on any specified VO. Or at least, if you'll be working with a JTree as I have, you'll want one soon. ;)

  • RELEVANCY SCORE 2.97

    DB:2.97:Urgent Renaming A Node In Jtree 7z


    I have a JTree with nodes created.Say one such node is named ABC
    I take in String from a JTextField and use this String to rename the node created.Say this String is ABCXYZ

    I use myDefaultMutableTreeNode.setUserObject("ABCXYZ") method to rename.

    The problem I face is as ABCXYZ is lengthier than ABC, the node appears like this ABC..... in JTree and when I select the node again ABCXYZ appears fully.

    How do I do set this right without deleting the node and adding a new one with ABCXYZ as the name??

    Thanks in advance

    DB:2.97:Urgent Renaming A Node In Jtree 7z

    Thanks both of you. both solutions work. but since an event gets triggered if I select the node I will use DefaultTreeModel.nodeStructureChanged(node) method

  • RELEVANCY SCORE 2.97

    DB:2.97:Drag N Drop From Jtree To Jtable Using Swing 7m


    Hi All,

    In my application, I want to drag and drop the node of the JTree to Jtable. How the Jtree node name added in the jtable as another row also after i added the row i want to open the frame with node name. Please help me.

    DB:2.97:Drag N Drop From Jtree To Jtable Using Swing 7m

    Take a look at this tutorial: [Introduction to DnD|http://java.sun.com/docs/books/tutorial/uiswing/dnd/intro.html]

  • RELEVANCY SCORE 2.96

    DB:2.96:Save Me!! About Jtree Refresh!! xd


    Hello ereryone. I met a problem and I tried lots of method,such as reload(),validate(),revalidate(),but it seemed that they doesn't work.

    My gui is about: here is a JSplitpane,on the left part ,there is a panel(borderlayou) in it. A button in the panel's west and a JScrollPane in the panel's center. A JTree component in the JScrollPane.

    The wished fountion is when the program run, the tree would show the demanded disk file system(read config file to get the root file).when u click the button, a JFilechooser come out and u can choose another dir of the disk. when u click "ok", the tree should show the new file structure of the new dir.

    here are 2 java file.
    //myclass.java
    //myclass.java
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.ImageIcon;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;

    import java.util.*;

    public class myclass extends JFrame implements WindowListener{

    private JFrame f=null;

    private JLabel labeladdress;
    private JLabel labelstatus;
    private JTree tree;
    private JSplitPane splitPane;
    private JEditorPane htmlPane;
    private JPopupMenu Popup=null;

    private DefaultTreeModel treeModel=null;
    private String str="";
    private boolean statusbarflag=true;
    private boolean addressbarflag=true;

    String currentpos;

    ImageIcon icon=new ImageIcon("icons/paste.gif");
    ReadAndWriteXML wp=new ReadAndWriteXML();

    public WebPageSave(Vector vec) throws FileNotFoundException, SecurityException,Exception{

    ////////////////
    ///////////////////////////
    wp.address_Vector=new Vector();
    wp.readXMLFile("sys/workposition.xml");
    //////////////////////////////////////

    f=new JFrame("WebHunter");
    Container contentPane=(JPanel)f.getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel panel=new JPanel();

    panel.setLayout(new BorderLayout());
    paneln.setLayout(new BorderLayout());
    contentPane.add(panel,BorderLayout.CENTER);
    contentPane.add(paneln,BorderLayout.NORTH);

    //#28155;#21152;JTree#21644;JEditorPane
    //JTree tree=new JTree();
    initialtree(wp.address_Vector.get(0).toString());

    final JScrollPane scrollPanel=new JScrollPane(tree);
    final JPanel mainleft=new JPanel(new BorderLayout());
    JButton jchange=new JButton("change position");
    currentpos=wp.address_Vector.get(0).toString();

    //the button anonymous class
    jchange.addActionListener(new ActionListener(){ //change the dir
    public void actionPerformed(ActionEvent event){
    JFileChooser chooser=new JFileChooser(currentpos);
    chooser.setDialogTitle("choose ur position");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int result=chooser.showDialog(f,"ok");
    if(result==JFileChooser.APPROVE_OPTION){
    int i=JOptionPane.showConfirmDialog(f,"make sure#65311;","notice",JOptionPane.YES_NO_OPTION);
    if(i==JOptionPane.YES_OPTION){

    try{
    //ReadAndWriteXML wp=new ReadAndWriteXML();
    wp.address_Vector=new Vector();
    wp.readXMLFile("sys/workposition.xml");
    FileOperation u=new FileOperation();
    u.xcopy(wp.address_Vector.get(0).toString(),chooser.getSelectedFile().toString());
    u.delete(new File(wp.address_Vector.get(0).toString()));
    }catch(Exception e){
    e.printStackTrace();
    }

    //write the new positon to the workposition.xml#25991;#20214;
    try{
    wp.writeXMLFile("sys/workposition.xml",chooser.getSelectedFile().toString());
    }catch (Exception e) {
    e.printStackTrace();
    }

    ?????? //refresh tree
    try{
    ReadAndWriteXML wp=new ReadAndWriteXML();
    wp.address_Vector=new Vector();
    wp.readXMLFile("sys/workposition.xml");

    currentpos=wp.address_Vector.get(0).toString();
    //currentpos=chooser.getSelectedFile().toString();
    //initialtree(wp.address_Vector.get(0).toString());
    initialtree(chooser.getSelectedFile().toString());
    //JScrollPane scrollPanel=new JScrollPane(tree);
    //mainleft.add(scrollPanel,BorderLayout.CENTER);
    //tree.
    //mainleft.validate();

    JOptionPane.showConfirmDialog(f,"change positon successfully#65281;","notice",JOptionPane.CLOSED_OPTION);
    }catch (Exception e1) {
    e1.printStackTrace();
    }
    }
    }
    }
    });

    mainleft.add(scrollPanel,BorderLayout.CENTER);
    mainleft.add(jchange,BorderLayout.SOUTH);
    JScrollPane scrollPane2=new JScrollPane(htmlPane);
    splitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,mainleft,scrollPane2);
    splitPane.setDividerSize(10);
    splitPane.setDividerLocation(180);
    panel.add(splitPane,BorderLayout.CENTER);
    panel.add(labelstatus,BorderLayout.SOUTH);

    f.pack();
    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    f.setExtendedState(Frame.MAXIMIZED_BOTH);
    f.setIconImage(icon.getImage());
    //f.setBounds(0,0,1020,725);
    f.show();
    //f.addWindowListener(new WindowListenerHandle());
    f.addWindowListener(this);

    }//constructor over!!!

    public void initialtree(String s) throws FileNotFoundException,SecurityException,Exception{

    //ReadAndWriteXML treefile=new ReadAndWriteXML();
    //treefile.address_Vector=new Vector();
    //treefile.readXMLFile("sys/workposition.xml");

    //tree=new FileTree(s);
    //tree.revalidate();
    //((DefaultTreeModel)tree.getModel()).nodeStructureChanged((DefaultTreeModel)s);
    tree=new showDir().initTree(s);
    tree.revalidate();
    //DefaultTreeModel model=new DefaultTreeModel(tree.getModel());
    //treeModel=(DefaultTreeModel) tree.getModel();
    //tree.setModel(model);
    //treeModel.reload();
    tree.setEditable(true);
    }
    //FileTree.java
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.util.*;

    public class FileTree extends JTree {
    private static DefaultTreeModel model;
    public FileTree(String path) throws FileNotFoundException, SecurityException {
    super((TreeModel)null); // Create the JTree itself

    // Use horizontal and vertical lines
    putClientProperty("JTree.lineStyle", "Angled");

    // Create the first node
    FileTreeNode rootNode = new FileTreeNode(null, path);

    model=new DefaultTreeModel(rootNode);
    // Populate the root node with its subdirectories
    boolean addedNodes = rootNode.populateDirectories(true);
    //model.nodeStructureChanged(rootNode);

    setModel(new DefaultTreeModel(rootNode));

    //(new DefaultTreeModel(rootNode))this.getModel().reload();
    //model.reload();
    // Listen for Tree Selection Events
    addTreeExpansionListener(new TreeExpansionHandler());
    }

    // Returns the full pathname for a path, or null if not a known path
    public String getPathName(TreePath path) {
    Object o = path.getLastPathComponent();
    if (o instanceof FileTreeNode) {
    return ((FileTreeNode)o).file.getAbsolutePath();
    }
    return null;
    }

    // Returns the File for a path, or null if not a known path
    public File getFile(TreePath path) {
    Object o = path.getLastPathComponent();
    if (o instanceof FileTreeNode) {
    return ((FileTreeNode)o).file;
    }
    return null;
    }

    // Inner class that represents a node in this file system tree
    protected static class FileTreeNode extends DefaultMutableTreeNode {
    public FileTreeNode(File parent, String name)
    throws SecurityException, FileNotFoundException {

    this.name = name;

    // See if this node exists and whether it is a directory
    file = new File(parent, name);
    if (!file.exists()) {
    throw new FileNotFoundException("File " + name + " does not exist");
    }

    isDir = file.isDirectory();

    // Hold the File as the user object.
    setUserObject(file);
    }

    // Override isLeaf to check whether this is a directory
    public boolean isLeaf() {
    return !isDir;
    }

    // Override getAllowsChildren to check whether this is a directory
    public boolean getAllowsChildren() {
    return !isDir;
    }

    // For display purposes, we return our own name
    public String toString() {
    return name;
    }

    // If we are a directory, scan our contents and populate
    // with children. In addition, populate those children
    // if the "descend" flag is true. We only descend once,
    // to avoid recursing the whole subtree.
    // Returns true if some nodes were added
    boolean populateDirectories(boolean descend) {
    boolean addedNodes = false;

    // Do this only once
    if (populated == false) {
    if (interim == true) {
    // We have had a quick look here before:
    // remove the dummy node that we added last time
    removeAllChildren();
    interim = false;
    }

    String[] names = file.list(); // Get list of contents

    // Process the directories
    for (int i = 0; i names.length; i++) {
    String name = names;
    File d = new File(file, name);
    try {
    FileTreeNode node = new FileTreeNode(file, name);
    if (d.isDirectory()) {
    //FileTreeNode node = new FileTreeNode(file, name);
    this.add(node);
    if (descend) {
    node.populateDirectories(false);
    }
    addedNodes = true;
    if (descend == false) {
    // Only add one node if not descending
    break;
    }
    }
    else{
    //FileTreeNode node = new FileTreeNode(file,name);
    this.add((MutableTreeNode)node);
    }

    //model.reload();
    //model.nodeStructureChanged(node);
    //((DefaultTreeModel)parent.getModel()).nodeStructureChanged(node);
    } catch (Throwable t) {
    // Ignore phantoms or access problems
    }
    }

    // If we were scanning to get all subdirectories,
    // or if we found no subdirectories, there is no
    // reason to look at this directory again, so
    // set populated to true. Otherwise, we set interim
    // so that we look again in the future if we need to
    if (descend == true || addedNodes == false) {
    populated = true;
    } else {
    // Just set interim state
    interim = true;
    }
    }
    return addedNodes;
    }

    protected File file; // File object for this node
    protected String name; // Name of this node
    protected boolean populated;// true if we have been populated
    protected boolean interim; // true if we are in interim state
    protected boolean isDir; // true if this is a directory
    }

    // Inner class that handles Tree Expansion Events
    protected class TreeExpansionHandler implements TreeExpansionListener {
    public void treeExpanded(TreeExpansionEvent evt) {
    TreePath path = evt.getPath(); // The expanded path
    JTree tree = (JTree)evt.getSource(); // The tree

    // Get the last component of the path and
    // arrange to have it fully populated.
    FileTreeNode node = (FileTreeNode)path.getLastPathComponent();
    if (node.populateDirectories(true)) {
    ((DefaultTreeModel)tree.getModel()).nodeStructureChanged(node);
    }
    }

    public void treeCollapsed(TreeExpansionEvent evt) {
    // Nothing to do
    }
    }
    }

    DB:2.96:Save Me!! About Jtree Refresh!! xd

    Hello ereryone. I met a problem and I tried lots of method,such as reload(),validate(),revalidate(),but it seemed that they doesn't work.

    My gui is about: here is a JSplitpane,on the left part ,there is a panel(borderlayou) in it. A button in the panel's west and a JScrollPane in the panel's center. A JTree component in the JScrollPane.

    The wished fountion is when the program run, the tree would show the demanded disk file system(read config file to get the root file).when u click the button, a JFilechooser come out and u can choose another dir of the disk. when u click "ok", the tree should show the new file structure of the new dir.

    here are 2 java file.
    //myclass.java
    //myclass.java
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.ImageIcon;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;

    import java.util.*;

    public class myclass extends JFrame implements WindowListener{

    private JFrame f=null;

    private JLabel labeladdress;
    private JLabel labelstatus;
    private JTree tree;
    private JSplitPane splitPane;
    private JEditorPane htmlPane;
    private JPopupMenu Popup=null;

    private DefaultTreeModel treeModel=null;
    private String str="";
    private boolean statusbarflag=true;
    private boolean addressbarflag=true;

    String currentpos;

    ImageIcon icon=new ImageIcon("icons/paste.gif");
    ReadAndWriteXML wp=new ReadAndWriteXML();

    public WebPageSave(Vector vec) throws FileNotFoundException, SecurityException,Exception{

    ////////////////
    ///////////////////////////
    wp.address_Vector=new Vector();
    wp.readXMLFile("sys/workposition.xml");
    //////////////////////////////////////

    f=new JFrame("WebHunter");
    Container contentPane=(JPanel)f.getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel panel=new JPanel();

    panel.setLayout(new BorderLayout());
    paneln.setLayout(new BorderLayout());
    contentPane.add(panel,BorderLayout.CENTER);
    contentPane.add(paneln,BorderLayout.NORTH);

    //#28155;#21152;JTree#21644;JEditorPane
    //JTree tree=new JTree();
    initialtree(wp.address_Vector.get(0).toString());

    final JScrollPane scrollPanel=new JScrollPane(tree);
    final JPanel mainleft=new JPanel(new BorderLayout());
    JButton jchange=new JButton("change position");
    currentpos=wp.address_Vector.get(0).toString();

    //the button anonymous class
    jchange.addActionListener(new ActionListener(){ //change the dir
    public void actionPerformed(ActionEvent event){
    JFileChooser chooser=new JFileChooser(currentpos);
    chooser.setDialogTitle("choose ur position");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int result=chooser.showDialog(f,"ok");
    if(result==JFileChooser.APPROVE_OPTION){
    int i=JOptionPane.showConfirmDialog(f,"make sure#65311;","notice",JOptionPane.YES_NO_OPTION);
    if(i==JOptionPane.YES_OPTION){

    try{
    //ReadAndWriteXML wp=new ReadAndWriteXML();
    wp.address_Vector=new Vector();
    wp.readXMLFile("sys/workposition.xml");
    FileOperation u=new FileOperation();
    u.xcopy(wp.address_Vector.get(0).toString(),chooser.getSelectedFile().toString());
    u.delete(new File(wp.address_Vector.get(0).toString()));
    }catch(Exception e){
    e.printStackTrace();
    }

    //write the new positon to the workposition.xml#25991;#20214;
    try{
    wp.writeXMLFile("sys/workposition.xml",chooser.getSelectedFile().toString());
    }catch (Exception e) {
    e.printStackTrace();
    }

    ?????? //refresh tree
    try{
    ReadAndWriteXML wp=new ReadAndWriteXML();
    wp.address_Vector=new Vector();
    wp.readXMLFile("sys/workposition.xml");

    currentpos=wp.address_Vector.get(0).toString();
    //currentpos=chooser.getSelectedFile().toString();
    //initialtree(wp.address_Vector.get(0).toString());
    initialtree(chooser.getSelectedFile().toString());
    //JScrollPane scrollPanel=new JScrollPane(tree);
    //mainleft.add(scrollPanel,BorderLayout.CENTER);
    //tree.
    //mainleft.validate();

    JOptionPane.showConfirmDialog(f,"change positon successfully#65281;","notice",JOptionPane.CLOSED_OPTION);
    }catch (Exception e1) {
    e1.printStackTrace();
    }
    }
    }
    }
    });

    mainleft.add(scrollPanel,BorderLayout.CENTER);
    mainleft.add(jchange,BorderLayout.SOUTH);
    JScrollPane scrollPane2=new JScrollPane(htmlPane);
    splitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,mainleft,scrollPane2);
    splitPane.setDividerSize(10);
    splitPane.setDividerLocation(180);
    panel.add(splitPane,BorderLayout.CENTER);
    panel.add(labelstatus,BorderLayout.SOUTH);

    f.pack();
    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    f.setExtendedState(Frame.MAXIMIZED_BOTH);
    f.setIconImage(icon.getImage());
    //f.setBounds(0,0,1020,725);
    f.show();
    //f.addWindowListener(new WindowListenerHandle());
    f.addWindowListener(this);

    }//constructor over!!!

    public void initialtree(String s) throws FileNotFoundException,SecurityException,Exception{

    //ReadAndWriteXML treefile=new ReadAndWriteXML();
    //treefile.address_Vector=new Vector();
    //treefile.readXMLFile("sys/workposition.xml");

    //tree=new FileTree(s);
    //tree.revalidate();
    //((DefaultTreeModel)tree.getModel()).nodeStructureChanged((DefaultTreeModel)s);
    tree=new showDir().initTree(s);
    tree.revalidate();
    //DefaultTreeModel model=new DefaultTreeModel(tree.getModel());
    //treeModel=(DefaultTreeModel) tree.getModel();
    //tree.setModel(model);
    //treeModel.reload();
    tree.setEditable(true);
    }
    //FileTree.java
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.util.*;

    public class FileTree extends JTree {
    private static DefaultTreeModel model;
    public FileTree(String path) throws FileNotFoundException, SecurityException {
    super((TreeModel)null); // Create the JTree itself

    // Use horizontal and vertical lines
    putClientProperty("JTree.lineStyle", "Angled");

    // Create the first node
    FileTreeNode rootNode = new FileTreeNode(null, path);

    model=new DefaultTreeModel(rootNode);
    // Populate the root node with its subdirectories
    boolean addedNodes = rootNode.populateDirectories(true);
    //model.nodeStructureChanged(rootNode);

    setModel(new DefaultTreeModel(rootNode));

    //(new DefaultTreeModel(rootNode))this.getModel().reload();
    //model.reload();
    // Listen for Tree Selection Events
    addTreeExpansionListener(new TreeExpansionHandler());
    }

    // Returns the full pathname for a path, or null if not a known path
    public String getPathName(TreePath path) {
    Object o = path.getLastPathComponent();
    if (o instanceof FileTreeNode) {
    return ((FileTreeNode)o).file.getAbsolutePath();
    }
    return null;
    }

    // Returns the File for a path, or null if not a known path
    public File getFile(TreePath path) {
    Object o = path.getLastPathComponent();
    if (o instanceof FileTreeNode) {
    return ((FileTreeNode)o).file;
    }
    return null;
    }

    // Inner class that represents a node in this file system tree
    protected static class FileTreeNode extends DefaultMutableTreeNode {
    public FileTreeNode(File parent, String name)
    throws SecurityException, FileNotFoundException {

    this.name = name;

    // See if this node exists and whether it is a directory
    file = new File(parent, name);
    if (!file.exists()) {
    throw new FileNotFoundException("File " + name + " does not exist");
    }

    isDir = file.isDirectory();

    // Hold the File as the user object.
    setUserObject(file);
    }

    // Override isLeaf to check whether this is a directory
    public boolean isLeaf() {
    return !isDir;
    }

    // Override getAllowsChildren to check whether this is a directory
    public boolean getAllowsChildren() {
    return !isDir;
    }

    // For display purposes, we return our own name
    public String toString() {
    return name;
    }

    // If we are a directory, scan our contents and populate
    // with children. In addition, populate those children
    // if the "descend" flag is true. We only descend once,
    // to avoid recursing the whole subtree.
    // Returns true if some nodes were added
    boolean populateDirectories(boolean descend) {
    boolean addedNodes = false;

    // Do this only once
    if (populated == false) {
    if (interim == true) {
    // We have had a quick look here before:
    // remove the dummy node that we added last time
    removeAllChildren();
    interim = false;
    }

    String[] names = file.list(); // Get list of contents

    // Process the directories
    for (int i = 0; i names.length; i++) {
    String name = names;
    File d = new File(file, name);
    try {
    FileTreeNode node = new FileTreeNode(file, name);
    if (d.isDirectory()) {
    //FileTreeNode node = new FileTreeNode(file, name);
    this.add(node);
    if (descend) {
    node.populateDirectories(false);
    }
    addedNodes = true;
    if (descend == false) {
    // Only add one node if not descending
    break;
    }
    }
    else{
    //FileTreeNode node = new FileTreeNode(file,name);
    this.add((MutableTreeNode)node);
    }

    //model.reload();
    //model.nodeStructureChanged(node);
    //((DefaultTreeModel)parent.getModel()).nodeStructureChanged(node);
    } catch (Throwable t) {
    // Ignore phantoms or access problems
    }
    }

    // If we were scanning to get all subdirectories,
    // or if we found no subdirectories, there is no
    // reason to look at this directory again, so
    // set populated to true. Otherwise, we set interim
    // so that we look again in the future if we need to
    if (descend == true || addedNodes == false) {
    populated = true;
    } else {
    // Just set interim state
    interim = true;
    }
    }
    return addedNodes;
    }

    protected File file; // File object for this node
    protected String name; // Name of this node
    protected boolean populated;// true if we have been populated
    protected boolean interim; // true if we are in interim state
    protected boolean isDir; // true if this is a directory
    }

    // Inner class that handles Tree Expansion Events
    protected class TreeExpansionHandler implements TreeExpansionListener {
    public void treeExpanded(TreeExpansionEvent evt) {
    TreePath path = evt.getPath(); // The expanded path
    JTree tree = (JTree)evt.getSource(); // The tree

    // Get the last component of the path and
    // arrange to have it fully populated.
    FileTreeNode node = (FileTreeNode)path.getLastPathComponent();
    if (node.populateDirectories(true)) {
    ((DefaultTreeModel)tree.getModel()).nodeStructureChanged(node);
    }
    }

    public void treeCollapsed(TreeExpansionEvent evt) {
    // Nothing to do
    }
    }
    }

  • RELEVANCY SCORE 2.96

    DB:2.96:Jtree Get Selected Node/Object Values mf


    I wan to get all the selected nodes/objects values that I added to the JTree. How can I do this?

    Thanks.

    DB:2.96:Jtree Get Selected Node/Object Values mf

    TreePath[] paths = tree.getSelectedPath();
    for(int i = 0; i paths.length; i++){
    TreeNode node = (TreeNode)paths.getLastPathComponent();
    Object mySelectedObject = node.getUserObject();
    }Some minor Errors

    We have to use array paths[i] instead of paths

    The correct code as used by me is

    javax.swing.tree.TreePath[] paths = jTree1.getSelectionModel().getSelectionPaths();
    for(int i = 0; i paths.length; i++){
    javax.swing.tree.TreeNode node = (javax.swing.tree.TreeNode)paths.getLastPathComponent();
    System.out.println(((javax.swing.tree.DefaultMutableTreeNode)node).getUserObject());
    }

    CSJakharia

  • RELEVANCY SCORE 2.95

    DB:2.95:How To Get The Index For A Jtree Node?? kp


    Dear friends:
    I use following code to get the node for JTRee:
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;for the selected currect node, How to get the Index for this JTree Node??

    I konw the method node.getIndex(0); etc to get the node value for each number, but how to get the Index for this Node??
    Any good code example??

    Thanks

    sunny

    DB:2.95:How To Get The Index For A Jtree Node?? kp

    Dear friends:
    I use following code to get the node for JTRee:
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;for the selected currect node, How to get the Index for this JTree Node??

    I konw the method node.getIndex(0); etc to get the node value for each number, but how to get the Index for this Node??
    Any good code example??

    Thanks

    sunny

  • RELEVANCY SCORE 2.95

    DB:2.95:Get All Nodes In A Tree c7


    Can somebody tell me how to get all the node objects (DefaultMutableTreeNode) that are there in JTree?
    Suppose I have created a tree and added 4 nodes to the same, and if I want to get dynamically all the nodes that are there in the tree, what should I do?
    Please help me..as it is urgent

    Thanx in Advance

    Novi

    DB:2.95:Get All Nodes In A Tree c7

    If you check the documentation to DefaultMutableTreeNode you see that some methods return enumerations, for example postorderEnumeration. You can use these to traverse the tree,
    DefaultMutableTreeNode root = ....; // start node.
    Enumeration e = root.postorderEnumeration(); // get wanted enumeration
    while (e.hasMoreElements()) { // all nodes
    DefaultMutableTreeNode node =
    (DefaultMutableTreeNode)e.nextElement(); // get node

    // do something with the node
    }PS. The code compiles but I havent actually run it :(

  • RELEVANCY SCORE 2.94

    DB:2.94:Jtree Node Selection fp


    Hi,

    I am having a JTree.
    In this jtree, i am having various levels of node.

    Take for example,my jtree contains structure like this....

    Computer(Top Root Node)
    Languages (first child node)
    Java (node under Languages)
    C ++ (node under Languages)
    C (node under Languages)

    OS (Second Child Node)
    Windows (node under OS)
    Unix (node under OS)

    If i delete the node "C++", then i need to select node "Java" after deletion.

    Here i am able to get the detail of the next sibling using getNextSibling().

    But how to select the next sibling ???
    Itz very urgent...Please help me out....
    Any help would be greatly appreciated..

    Thanks,
    Manikandan

    DB:2.94:Jtree Node Selection fp

    Hi,

    I am having a JTree.
    In this jtree, i am having various levels of node.

    Take for example,my jtree contains structure like this....

    Computer(Top Root Node)
    Languages (first child node)
    Java (node under Languages)
    C ++ (node under Languages)
    C (node under Languages)

    OS (Second Child Node)
    Windows (node under OS)
    Unix (node under OS)

    If i delete the node "C++", then i need to select node "Java" after deletion.

    Here i am able to get the detail of the next sibling using getNextSibling().

    But how to select the next sibling ???
    Itz very urgent...Please help me out....
    Any help would be greatly appreciated..

    Thanks,
    Manikandan

  • RELEVANCY SCORE 2.93

    DB:2.93:Color Of Nodes In Jtree ck


    Hi,

    how can you change the color of the nodes displayed in a JTree?
    I want the color of each node to depend on the node's name, since I am using JTree to represent various categories of things...

    Thanks in advance...

    DB:2.93:Color Of Nodes In Jtree ck

    Yes, that worked just fine!!!

    Thanks Marcin!

  • RELEVANCY SCORE 2.92

    DB:2.92:Treenodeschanged Only Called When Root Changes jx


    Hi all, just a quick one,

    I have a JTree and TreeModel setup, and set up a tree model listener as follows:

    public void treeNodesChanged(TreeModelEvent treeModelEvent) {
    // The user has changed the name of a node
    System.out.println("TREENODES CHANGED");
    }But this only gets called when the root node is changed. When the other (leaf) nodes are changed (by changed, i mean double-clicking the node and changing the title of it in the tree GUI) everything goes through ok (my model is changed properly with setUserObject ), but treeNodesChanged doesn't get called... :-S

    Any hints?

    DB:2.92:Treenodeschanged Only Called When Root Changes jx

    Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and/or
    http://riters.com/JINX/index.cgi/Suggestions_20for_20Asking_20Questions_20on_20Newsgroups

  • RELEVANCY SCORE 2.90

    DB:2.90:How To Get The Bounds Of The Root Handlers In A Jtree mz


    Hi all,

    Is there any way of get the bounds of the expand-control component of a node within a JTree?.

    I mean something like the protected method method BasicTreeUI.isLocationInExpandControl or analogous to the JTree methods getPathBounds/get.RowBounds.

    Thanks in advance.

    DB:2.90:How To Get The Bounds Of The Root Handlers In A Jtree mz

    Hi,

    I'm working with a JTreeTable (concretely with the implementation given at http://cal007300.student.utwente.nl/treetables/). I want to expand the tree whenever the user double-click over the cell that "contains" a node, it is just a fancy, and I do it by redirecting (actually sending a copy of) the event to the tree. Here is the code snippet (the enclosing class is a JTable):

    protected void processMouseEvent(MouseEvent e){

    if(getColumnClass(columnAtPoint(e.getPoint())) == TreeTableModel.class){
    int x = e.getX(), y = e.getY();

    // //Cheat the tree saying that the click were done over the node-component
    // //Problem with double clicks aggregated nodes root handlers
    // if(SwingUtilities.isLeftMouseButton(e) e.getClickCount() 1){
    // Rectangle r = tree.getRowBounds(rowAtPoint(e.getPoint()));
    // if(!r.contains(e.getPoint())){
    // x = r.x + 1;
    // y = r.y + 1;
    // }
    // }

    //Redirect the event to the tree
    MouseEvent treeEvent = new MouseEvent(tree,
    e.getID(),
    e.getWhen(),
    e.getModifiers(),
    x,
    y,
    e.getClickCount(),
    e.isPopupTrigger(),
    e.getButton());

    tree.dispatchEvent(treeEvent);
    }

    super.processMouseEvent(e);
    }The commented code is what I use to allow expanding the tree with a double-click at any point of its associated table-cell. The problem is that if I uncomment it, the mouse pointer location is also moved to the "node label" if there is a double click over the root-handler component, since this component is not within the bounds returned by getRowBounds method, and so the behavior of the tree is not that expected by the user (that is because I have commented it).

    I hope this is more understandable than my previous post.

  • RELEVANCY SCORE 2.89

    DB:2.89:Drag And Drop Between Jlist And Jtree 17


    Hi frnds,

    I want to write code to support Drag and Drop between JList and JTree. If i select a term in JList and drop it on any node in JList then a node should be created as child to that node with name as selected term inJList.

    If anybody implemented this code please post it here. I am in urgent need.

    Thanks in Advance

    -Best,
    LENIN.

    DB:2.89:Drag And Drop Between Jlist And Jtree 17

    Hi,

    Thank you....

    I have written code for that.

    Thanks once again.

    -Lenin.

  • RELEVANCY SCORE 2.88

    DB:2.88:Jtree Nodes Serialization zp


    I've a little problem. It's very easy to serialize Jtree, I've this code:

    public class Serializer
    {

    // -------------------------
    // saves JTree

    public static void write (DefaultTreeModel model, String filename)
    {
    XMLEncoder encoder = null;

    try { encoder = new XMLEncoder ( new BufferedOutputStream (new FileOutputStream(filename)));}
    catch (FileNotFoundException e) {e.printStackTrace();}

    encoder.writeObject(model);
    encoder.close();
    }

    // -------------------------
    // loads JTree

    public static DefaultTreeModel read (String filename)
    {
    XMLDecoder decoder = null;
    try {decoder = new XMLDecoder ( new BufferedInputStream (new FileInputStream(filename)));}
    catch (FileNotFoundException e) {e.printStackTrace();}

    DefaultTreeModel model = (DefaultTreeModel)decoder.readObject();
    decoder.close();

    return model;
    }
    }This works fine.
    BUT: I wanted a special node - with more informations, so I created a class Node

    public class Node
    {
    private String name;// name of node
    private boolean editable; // editable
    private String content;// content of node = some text

    // some getters and setters ...
    }And instances of class Node I put to JTree like this:
    Node node = new Node ("file123", true, "this is content");
    DefaultMutableTreeNode root = new DefaultMutableTreeNode (node);But when I want to save JTree to disc, it crashes and I get exception like this:

    java.lang.InstantiationException: Node
    Continuing ...
    java.lang.RuntimeException: failed to evaluate: unbound=Class.new();
    Continuing ...Simple, it writes nodes structure to file (whole tree with every node), but not the CONTENT of nodes (parameters name, editable and content). It's possible to save whole tree with all nodes (and each node with all parameters)?

    Thanx a lot.

    DB:2.88:Jtree Nodes Serialization zp

    You can get around this by defining a toString() method that returns 'name', but that implies that somebody is displaying Node.toString(), which it shouldn't - it should cast to Node and display Node.getName(). If this is your code fix that instead.

  • RELEVANCY SCORE 2.88

    DB:2.88:Jtree Right Click Selection za


    Hello

    I have a problem. I tried searching for the solution in the forum but nothing worked.
    I have a Jtree and when i right click on a node, i would like to get the value of the node clicked (its name, in other words.)

    This is what i did:

    equipmentTree.addMouseListener(new MouseAdapter()
    {
    public void mousePressed(MouseEvent e)
    {
    if (e.isPopupTrigger())
    {
    int row = equipmentTree.getRowForLocation(e.getX(),e.getY());
    equipmentTree.setSelectionInterval(row,row);
    }
    }
    public void mouseReleased(MouseEvent e)
    {
    if (e.isPopupTrigger())
    {
    int row = equipmentTree.getRowForLocation(e.getX(),e.getY());
    equipmentTree.setSelectionInterval(row,row);
    }
    }
    });How do i get the value of what i clicked on?

    Any help would be greatly appreciated.
    Thanks

    DB:2.88:Jtree Right Click Selection za

    Never mind you guys!!
    i found it!

    lol

    Thanks anyways!

  • RELEVANCY SCORE 2.88

    DB:2.88:Jtree - Problems With Names Of Elements zd


    I have a Jtree thats populated with expandable elements. These elements are loaded on startup, but some of the elements don't get their full names, just i.e "dem..." instead of "demo3". WHen I expand the node, the full name appears, and remains.

    Anyone know what this could be?
    The problem is really often associated with nodes with names containing "m" ..

    DB:2.88:Jtree - Problems With Names Of Elements zd

    I am also seeing this problem. Most of the time, the tree displays properly, but at seemingly random times, the names of tree items display shortened with a ... at the end. Seems like a bug in the JTree implementation.

    Has anyone found any workarounds to this?

  • RELEVANCY SCORE 2.86

    DB:2.86:Urgent !!!!Rendering A Jtree Node As A Table 7z


    Hi,
    Can we render a node of a JTree containg some data to a tabular format using JTable or some Model.
    regards
    Kaushik

    DB:2.86:Urgent !!!!Rendering A Jtree Node As A Table 7z

    Hi,
    Can we render a node of a JTree containg some data to a tabular format using JTable or some Model.
    regards
    Kaushik

  • RELEVANCY SCORE 2.86

    DB:2.86:(Jtree)Full Node Caption Is Not Visible sm


    Hello everyone,

    I am a novice swing developer.

    I have generated JTree by implementing TreeModel interface.

    I show node caption by overriding toString() metod of node object.

    Now on valueForPathChanged event i make changes in child node so node caption changes accordingly.

    But full node captions are not displayes instaead it shows partial name followed by ...

    Kindly suggest appropriate solution.

    DB:2.86:(Jtree)Full Node Caption Is Not Visible sm

    How do you write the valueForPathChanged function? Could you show the code?

  • RELEVANCY SCORE 2.86

    DB:2.86:Get Current Tree Select Node ff


    Hi,ALL

    I want to return JTree selection.

    As you know If use JTree object, we can use
    getSelectionPaths(), and use Treepah object method
    getLastPathComponent to get selected node.

    What I want to do is.

    My JTree Object model is DefaultMutableTreeNode

    i want to use DefaultMutableTreeNode to access selected Node.

    Can I do like this?
    If I can, how to do it?

    Thanks in advanced

    DB:2.86:Get Current Tree Select Node ff

    Hi,ALL

    I want to return JTree selection.

    As you know If use JTree object, we can use
    getSelectionPaths(), and use Treepah object method
    getLastPathComponent to get selected node.

    What I want to do is.

    My JTree Object model is DefaultMutableTreeNode

    i want to use DefaultMutableTreeNode to access selected Node.

    Can I do like this?
    If I can, how to do it?

    Thanks in advanced

  • RELEVANCY SCORE 2.85

    DB:2.85:Editing Nodes In Jtree m7



    I have a JTree in which the nodes are objects. So, just besides the node name, i store information such as ID,Status etc. I get problems when I edit nodes. JTree simply seems to put the edited "Name" instead of the complete object after the editing session ends. Could anyone please tell me how to solve this problem? Thanks

    DB:2.85:Editing Nodes In Jtree m7

    Check out the tutorial === over there on using JTree

  • RELEVANCY SCORE 2.85

    DB:2.85:How To Get A Jtree And Set The Foregroundcolor Of A Node And Replace It? 8x


    I am having a JTree and I want to set the foreground color of all the visited nodes .
    How to do it?

    Please help me
    Its urgent.

    DB:2.85:How To Get A Jtree And Set The Foregroundcolor Of A Node And Replace It? 8x

    Answer is here:
    http://forum.java.sun.com/thread.jspa?threadID=768194tstart=0

  • RELEVANCY SCORE 2.85

    DB:2.85:How To Save Node In Database Feom Jtree sk


    how to save node in database feom JTree

  • RELEVANCY SCORE 2.85

    DB:2.85:Searching A Node In Jtree ps


    Hi
    I have to select node with the same name but in different hierarchy in Jtree and the other node may be visible or can be child of some collapsed tree node so how I will search that tree node in JTree . I want to select the next on click of next button so what I have to do to select that node as getNextMatch is giving only for the nodes immediate child of root node but its not going in to depth.
    Plz help me in finding solution for that
    Regards,
    Anoop

  • RELEVANCY SCORE 2.85

    DB:2.85:Changing The Text Of A Jtree Node 8p


    How can the text (not the name) of a node in a JTree be modified dynamically? I already know that the setEditable(boolean flag) allows you to manually modify the text via mouse click, but I want to change or setText dynamically from within the code.
    Sincerely,
    Robert

    DB:2.85:Changing The Text Of A Jtree Node 8p

    Never mind, I figured it out myself. Not sure what adverse side affects this may cause if any, but it works.
    See code below...
    nodeName.setUserObject(String newName);
    mytree.repaint(); // helps render new text without ellipsis

  • RELEVANCY SCORE 2.85

    DB:2.85:How To Reach At A Node Of Jtree : Urgent mx


    Hay all,
    Plz tell me that how to reach at a particular node in a JTree, whose name is known to you.I have used a DefaultTreeModel to create a tree. As

    deviceTreeModel=new DefaultTreeModel(rootNode);
    tree = new JTree( deviceTreeModel );

    Thanks and Regards,
    Sharad Agarwal

    DB:2.85:How To Reach At A Node Of Jtree : Urgent mx

    Hay all,
    Plz tell me that how to reach at a particular node in a JTree, whose name is known to you.I have used a DefaultTreeModel to create a tree. As

    deviceTreeModel=new DefaultTreeModel(rootNode);
    tree = new JTree( deviceTreeModel );

    Thanks and Regards,
    Sharad Agarwal

  • RELEVANCY SCORE 2.84

    DB:2.84:Adding New Nodes To Jtree 91


    Hi
    I am working on JTree .When i create a new node in and add it to Jtree i want to see the nod ein correct position Immediately

    If I have node1,node3 ,node4 as the treenodes in jtree.
    now when i create a new node called node2 and add it to Jtree i want to see the node after node1.

    but the problem i have is its adding at the end i.e node2 is added to jtree after node4.

    how do i get around the problem and add the nodes to jtree as i require.

    Can anyone please suggest me a solution as soon as possible,if possible with some code

    thanks

    DB:2.84:Adding New Nodes To Jtree 91

    I think you are using something to insert node.

    treeModel.insertNodeInto(newNode,parentNode,
    parentNode.getChildCount());
    which adds to the end.

    Please try this

    javax.swing.tree.DefaultTreeModel.getIndexOfChild(parentnode,node1)

    This will give you the index of node1.
    Then call
    treeModel.insertNodeInto(newKeyCardNode,newGroupNode,
    index+1);

    May be this will help

  • RELEVANCY SCORE 2.84

    DB:2.84:Jtree 81


    how can i get node's name
    i tried Node.getName() but it didnt work

    DB:2.84:Jtree 81

    Use node.getUserObject()

  • RELEVANCY SCORE 2.84

    DB:2.84:Jtree Problem 8m


    Hi All,

    I would like some help with the following question.

    I need to insert a JButton into node of JTree after name of the node.
    Also I need handle the events from this button properly (For example:
    when I press on button needn't tree node open).

    How do you usually deal with the problem?

    Thanks,

    Andrey.

    DB:2.84:Jtree Problem 8m

    You should probably build your own custom treeRenderer to handle adding a button..

  • RELEVANCY SCORE 2.84

    DB:2.84:Jtree - Userobject jc


    Hello,

    - JTree consists of nodes.
    - Each node has its own userObject.
    - An userObject contains node specific information, like node-name etc.

    Is there also a userObject for the JTree it self?

    I have 2 Classes.
    Class 1: Creates JTree
    Class 2: Access to Class 1 and get JTree

    If I create the JTree, I want just to set a flag (true/false).
    If I get the JTree, I want to read this flag from the JTree-object.

    How do I do this, any hint?

    -many thanks
    Aykut

    DB:2.84:Jtree - Userobject jc

    a picture says more than 1000 words

    http://www.mdlsoft.co.uk/PrimaryPics1/thanks.jpg

  • RELEVANCY SCORE 2.84

    DB:2.84:Jtree Of Files Is Very Slow 89


    I want to write file chooser in form of JTree. It works well enough with one problem - when displaying content of "My Computer" - whole application hangs for 5-15 seconds. Even when it already was displayed (and cached inside it's parent node) it still takes lots of time to scroll up to A:. I can't understand why because it takes milliseconds for JFileChooser.

    Some details:
    I never read for child files again - they are cached. Same for icon and name. I am using JFileChooser methods to get both icon and name.

    DB:2.84:Jtree Of Files Is Very Slow 89

    If you're truly caching the children of parent nodes, it shouldn't be slow. Since you say

    it still takes lots of time to scroll up to A:the issue could be in your custom TreeCellRenderer (since it's called whenever you scroll).

    The short answer is: post an SSCCE if you need further help. Note that an SSCCE is not your entire current application.

  • RELEVANCY SCORE 2.84

    DB:2.84:Jtree De-Highlight Node 3p


    I have a JTree with DefaultMutableTreeNode-s
    I am using a SINGLE_SELECTION_MODE model

    When I use the mouse to select a node in the JTree, it automatically highlights that node. What should I use if I want to be able to use the mouse to de-select the node and remove the highlight?

    -andrew

    DB:2.84:Jtree De-Highlight Node 3p

    CTRL-click the node to de-select it.

  • RELEVANCY SCORE 2.83

    DB:2.83:Jtree Behaviour 9c


    Hi guys;

    i want to implement the next behaviour for a Jtree:

    suppose that my JTree is filled with nodes like: colors, sports ...and their leafs also...
    when i click a node or leaf i want to be able to get the value of the selected node: ( i.e here: colors or sports..)

    do i have to add a Listener to my JTree? how can i then do this job?

    thanks for help!

    DB:2.83:Jtree Behaviour 9c

    You should implements TreeWillExpandListener or TreeSelectionListener.. First one allows you to catch events that occur when you click a node to expand it and the other one occurs when you actually select a node.. so pick one or both..

    to implements TreeWillExpandListener you need methods
    public void treeWillExpand(TreeExpansionEvent event)
    throws ExpandVetoException
    {
    // You can use these to get either the path or just the text on nodes..
    //event.getPath().getPath();
    //event.getPath().getLastPathComponent();
    }

    public void treeWillCollapse(TreeExpansionEvent event)
    {
    //do something if this intrest..
    }SelectionListener need following method:
    public void valueChanged(TreeSelectionEvent event)
    {
    // You can use these to get either the path or just the text on nodes..
    //event.getPath().getPath();
    //event.getPath().getLastPathComponent();
    } and of course attact the lsitener to the JTree (here assumed that the instance that creates the JTree also implementent the interfaces)
    addTreeWillExpandListener(this);
    addTreeSelectionListener(this);Hope this helps,
    P_s

  • RELEVANCY SCORE 2.83

    DB:2.83:How To Get Jtree-Node Values Returned?? pc


    I'm having problems in getting the value of JTree Nodes.How can a JTree Node return its value.

    Regards

    Kamran

    DB:2.83:How To Get Jtree-Node Values Returned?? pc

    How can i get the values even without any event being triggered. What i need is to get a node value when i just have a tree object which has the entire tree.

  • RELEVANCY SCORE 2.83

    DB:2.83:How To Get A Value Of Node In Jtree? s8


    I want to get the values of the all the nodes of JTree one by one, how can I do this? Thanks!

    DB:2.83:How To Get A Value Of Node In Jtree? s8

    Use getRoot() in TreeModel or DefaultTreeModel (can't remember where it was) to get the root.

    then make a fuction like this:
    treeiter(TreeNode tn)
    {
    for (int i=0;itn.getchildCount();i++)
    {
    treeiter(tn.getChildAt(i));
    }
    somefunction(tn); or tn.somefunction;
    }

  • RELEVANCY SCORE 2.83

    DB:2.83:Problems With Jtree sj


    Hi all,

    I have a JTree application which is deployed in a client server environment. It is an Applet where I need to form a Tree structure showing argumentation.

    When I try adding a node to another node, I get the following exception.

    java.lang.NumberFormatException: For input string: "ct"

    I was trying to track the statement that was giving the exception and found out that the statement -

    treeModel.insertNodeInto(childNode, parent, parent.getChildCount());

    is giving the exception. Due to this all the nodes get added to the RootNode.

    Here treeModel is a DefaultTreeModel(). childNode is the node being added and parent is the node to which the child is being added.

    Previously it was working very fine, but I have no clue why this is happening suddenly.

    Please help me, very urgent.

    Thanks in advance

  • RELEVANCY SCORE 2.82

    DB:2.82:How To Set One Row Or Node 'S Height In The Jtree? pa


    How to set height of one row or node in the jtree?
    I found the method :jTree.setRowHeight(height);.
    But I want to set height of one row ,not all rows of a jtree.

    Thanks for help!

  • RELEVANCY SCORE 2.81

    DB:2.81:Custom Treecellrenderer Not Working In Program d1


    The following 2 lines set my TreeCellRenderer

    FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
    jtree.setCellRenderer(renderer1);

    Rendering is not working in the Below Program. But If I comment the above 2 lines the default rendering is working. There is a probelm with my rendering class FSDirectoryCellRenderer which I am not able to figure out. PLease help me out

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;

    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.SoftBevelBorder;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;

    public class UniversityLayout extends JFrame {

    private JTree jtree = null;
    private DefaultTreeModel defaultTreeModel = null;
    private JTextField jtfStatus;

    public UniversityLayout() {
    super("A University JTree Example");
    setSize(300, 300);

    Object[] nodes = buildJTree();

    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
    renderer.setOpenIcon(new ImageIcon("opened.gif"));
    renderer.setClosedIcon(new ImageIcon("closed.gif"));
    renderer.setLeafIcon(new ImageIcon("leaf.gif"));
    jtree.setCellRenderer(renderer);
    jtree.setShowsRootHandles(true);
    jtree.setEditable(false);

    jtree.addTreeSelectionListener(new UTreeSelectionListener());
    FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
    jtree.setCellRenderer(renderer1);

    JScrollPane s = new JScrollPane();
    s.getViewport().add(jtree);
    getContentPane().add(s, BorderLayout.CENTER);

    jtfStatus = new JTextField(); // Use JTextField to allow copy operation
    jtfStatus.setEditable(false);
    jtfStatus.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
    getContentPane().add(jtfStatus, BorderLayout.SOUTH);

    TreePath path = new TreePath(nodes);
    jtree.setSelectionPath(path);
    //jtree.scrollPathToVisible(path);
    }

    class FSDirectoryCellRenderer extends JLabel implements TreeCellRenderer {

    private Color textSelectionColor;

    private Color textNoSelectionColor;

    private Color backgroundSelectionColor;

    private Color backgroundNoSelectionColor;

    private boolean sel;

    public FSDirectoryCellRenderer() {
    super();

    textSelectionColor = UIManager.getColor("Tree.selectionForeground");
    textNoSelectionColor = UIManager.getColor("Tree.textForeground");
    backgroundSelectionColor = UIManager
    .getColor("Tree.selectionBackground");
    backgroundNoSelectionColor = UIManager
    .getColor("Tree.textBackground");
    setOpaque(false);

    }

    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean selected, boolean expanded, boolean leaf, int row,
    boolean hasFocus) {

    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    Object obj = node.getUserObject();
    setText(obj.toString());

    if (obj instanceof Boolean) {
    setText("Loading");
    }

    if (obj instanceof NodeIconData) {
    NodeIconData nodeIconData = (NodeIconData) obj;
    if (expanded) {
    setIcon(nodeIconData.getExpandedIcon());
    } else {
    setIcon(nodeIconData.getNormalIcon());
    }
    } else {
    setIcon(null);
    }
    setFont(jtree.getFont());
    setForeground(selected ? textSelectionColor : textNoSelectionColor);
    setBackground(selected ? backgroundSelectionColor
    : backgroundNoSelectionColor);

    sel = selected;
    return this;
    }

    }
    private Object[] buildJTree() {
    Object[] nodes = new Object[4];
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(new College(1, "College"));
    DefaultMutableTreeNode parent = root;
    nodes[0] = root;

    DefaultMutableTreeNode node = new DefaultMutableTreeNode(new College(2, "Class 1"));
    parent.add(node);
    parent = node;
    parent.add(new DefaultMutableTreeNode(new College(3, "Section A")));
    parent.add(new DefaultMutableTreeNode(new College(4, "Section B")));
    parent = root;

    node = new DefaultMutableTreeNode(new College(5, "Class 2"));
    parent.add(node);
    nodes[1] = node;
    parent = node;

    node = new DefaultMutableTreeNode(new College(6, "Science"));
    parent.add(node);
    //nodes[2] = node;
    parent = node;
    parent.add(new DefaultMutableTreeNode(new College(7, "Computer Science")));
    parent.add(new DefaultMutableTreeNode(new College(8, "Information Science")));
    parent = (DefaultMutableTreeNode)nodes[1];
    node = new DefaultMutableTreeNode(new College(9, "Arts"));
    parent.add(node);
    nodes[2] = node;
    parent = (DefaultMutableTreeNode)nodes[2];
    parent.add(new DefaultMutableTreeNode(new College(10, "Drawing")));
    node = new DefaultMutableTreeNode(new College(11, "Painting"));
    parent.add(node);
    nodes[3] = node;
    parent = (DefaultMutableTreeNode)nodes[1];
    parent.add(new DefaultMutableTreeNode(new College(12, "Telecom")));

    defaultTreeModel = new DefaultTreeModel(root);
    jtree = new JTree(defaultTreeModel);
    return nodes;
    }

    public static void main(String argv[]) {
    UniversityLayout frame = new UniversityLayout();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }

    class UTreeSelectionListener implements TreeSelectionListener {

    public void valueChanged(TreeSelectionEvent e) {
    TreePath path = e.getPath();
    Object[] nodes = path.getPath();
    String status = "";
    for (int k = 0; k nodes.length; k++) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes[k];
    College nd = (College) node.getUserObject();
    status += "." + nd.getId();
    }
    jtfStatus.setText(status);
    }
    }
    }

    class College {
    protected int id;

    protected String name;

    public College(int id, String name) {
    this.id = id;
    this.name = name;
    }

    public int getId() {
    return id;
    }

    public String getName() {
    return name;
    }

    public String toString() {
    return name;
    }
    }

    DB:2.81:Custom Treecellrenderer Not Working In Program d1

    I don't think my post went through last time, so I'm reposting. Sorry if you see this twice!

    You call "setOpaque(false)" on your renderer when you should be calling "setOpaque(true)". Your renderer is a JLabel which, by default, does not paint its background.

    Again though, is there any reason you're not using DefaultTreeCellRenderer? It looks like your custom renderer is just using default color values itself, so why not use the default?

  • RELEVANCY SCORE 2.81

    DB:2.81:Jtree And Jtable ms


    Hi i want to implement functionality where i can drag a node from JTree and drop it on JTable then a new row should get created in table and selected node should get deleted from JTree and vice varsa.

    can any one help me...?

    DB:2.81:Jtree And Jtable ms

    868031 wrote:
    Thanks for suggestion i will be happy if i get some code..... i have very less time to implement it.cool - I have a little bit of time to implement it for you, and will be happy if I get a good big bag of money for doing so :-)

    Cheers
    Jeanette

  • RELEVANCY SCORE 2.81

    DB:2.81:Custom Defaulttreecellrender Not Rending Node Labels Correctly. 7m


    In our JTree we need to display the state of our custom nodes, the state can be cycled by the user clicking on the node. Our problem is that since upgrading from Java 1.4 if a node is clicked before it is expanded the child nodes will not be rendered correclty, some nodes may not have the label showing, some may not have the label or icon showing.

    Under Java 1.4 the following code works correctly.
    Under Java 1.5 and 1.6 If you click on a node before expanding it (which changes the node's icon) then expand the node the child nodes are not completely rendered, some may be missing a icon or label or both.

    package com.test;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.FlowLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;

    import javax.swing.Box;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;

    /**
    * Example to demonstate differences between Java 1.4 and Java 1.5/1.6
    * node rendering.
    * p
    * Under Java 1.4 nodes are always rendered correctly.
    * p
    * Under Java 1.5 and 1.6 If you click on a node before expanding it (which
    * results in the icon changing) then expand the node not all child nodes
    * will be fully rendered.
    */
    public class TreeNodeRenderExample extends javax.swing.JFrame {

    private static final long serialVersionUID = 7963956320358601702L;

    private JTree tree1;

    /**
    * Entry point.
    *
    * @param args Arguments are ignored.
    */
    public static void main(String[] args) {
    TreeNodeRenderExample inst = new TreeNodeRenderExample();
    inst.setVisible(true);
    }

    /**
    * Constructor.
    * br
    * Create a instance of TreeNodeRenderExample.
    */
    public TreeNodeRenderExample() {
    super();
    initGUI();
    populateTree();
    postInitGUI();

    }

    /**
    * Create the Frame and JTree.
    */
    private void initGUI() {
    try {
    {
    this.setTitle("Checkbox node Render Example");
    }
    {
    tree1 = new JTree();
    getContentPane().add(tree1, BorderLayout.CENTER);
    }
    setSize(400, 300);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * Add the custom cell renderer and a mouse listener.
    */
    private void postInitGUI() {
    tree1.setCellRenderer(new NodeRenderer());
    tree1.addMouseListener(new TreeMouseClickSelectionListener(tree1));
    }

    /**
    * Populate the tree.
    */
    private void populateTree() {
    TreeNode root = new TreeNode("Render Example");
    TreeNode colourNode = new TreeNode("Colours");
    TreeNode modelNode = new TreeNode("Models");

    colourNode.add(new TreeNode("Black"));
    colourNode.add(new TreeNode("White"));
    colourNode.add(new TreeNode("Blue"));

    modelNode.add(new TreeNode("Ford"));
    modelNode.add(new TreeNode("Fiat"));
    modelNode.add(new TreeNode("Nissan"));

    root.add(modelNode);
    root.add(colourNode);

    tree1.setModel(new DefaultTreeModel(root));
    }

    /**
    * Custom tree node to allow the icon to be changed when the node
    * is clicked.
    * p
    * This is a simple example, our custom nodes hold much more state
    * information and get node children on the fly.
    */
    class TreeNode extends DefaultMutableTreeNode {

    private static final long serialVersionUID = 7527381850185157388L;

    /**
    * Constructor.
    * br
    * Create a instance of TreeNode.
    *
    * @param name Tree node display name.
    */
    public TreeNode(String name) {
    this.name = name;
    this.state = "u";
    }

    /**
    * Just cycle through some states so that the icon can
    * can be changed depending on how may 'clicks' on the node.
    */
    public void updateSelectionStatus() {
    if (state.equals("u")) {
    state = "s";
    } else if (state.equals("s")) {
    state = "d";
    } else if (state.equals("d")) {
    state = "u";
    }
    }

    /**
    * Get the icon to be used for the check box, shows the current
    * state of a node to the user.
    *
    * @return A icon.
    */
    public Icon getIcon() {
    Icon icon = null;

    if (state.equals("u")) {
    icon = UIManager.getIcon("FileView.directoryIcon");
    } else if (state.equals("s")) {
    icon = UIManager.getIcon("FileView.fileIcon");
    } else if (state.equals("d")) {
    icon = UIManager.getIcon("FileView.computerIcon");
    }

    return icon;
    }

    /**
    * String representation of a node.
    *
    * @see javax.swing.tree.DefaultMutableTreeNode#toString()
    */
    public String toString() {
    return name;
    }

    private String name;
    private String state;
    }

    /**
    * Custom node render, adds a checkbox in front of the node, could be
    * any object that we can change the icon for, this will show the
    * user the current state of the selected node.
    */
    class NodeRenderer extends DefaultTreeCellRenderer {

    private static final long serialVersionUID = -7358496302112018405L;

    protected JCheckBox checkBox = new JCheckBox();
    //protected JButton checkBox = new JButton();
    private Component strut = Box.createHorizontalStrut(5);
    private JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,0,0));

    /**
    * Constructor.
    */
    public NodeRenderer() {
    setOpaque(false);

    this.checkBox.setOpaque(false);

    this.panel.setBackground(UIManager.getColor("Tree.textBackground"));
    this.panel.setOpaque(false);

    this.panel.add(this.checkBox);
    this.panel.add(this.strut);
    this.panel.add(this);
    }

    /**
    * Render the label, then change the icon if necessary.
    *
    * @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean)
    */
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
    {
    super.getTreeCellRendererComponent(tree, value,
    sel, expanded, leaf, row, hasFocus);


    updateDisplayedStatus((TreeNode)value);

    return this.panel;
    }

    /**
    * Set the node's icon.
    *
    * @param node Rendered node.
    */
    private void updateDisplayedStatus(TreeNode node) {
    this.checkBox.setIcon(node.getIcon());
    }
    }

    /**
    * Listener to allow cycling of node states by clicking on the node.
    */
    class TreeMouseClickSelectionListener extends MouseAdapter {

    private JTree tree;
    private int hotspot = new JCheckBox().getPreferredSize().width;

    /**
    * Constructor.
    * br
    * Create a instance of TreeMouseClickSelectionListener.
    *
    * @param tree Tree listener is attached to.
    */
    public TreeMouseClickSelectionListener(JTree tree) {
    this.tree = tree;
    }

    /**
    * Cycle the state of a clicked node.
    *
    * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
    */
    public void mouseClicked(MouseEvent me) {
    int x = me.getX();
    int y = me.getY();
    int row = tree.getRowForLocation(x, y);
    TreePath path = tree.getPathForRow(row);

    if (path != null)
    {
    if(x = tree.getPathBounds(path).x + hotspot)
    {
    TreeNode node = (TreeNode) path
    .getLastPathComponent();

    if (node != null)
    {
    node.updateSelectionStatus();
    tree.repaint();
    }
    }
    }
    }

    }
    }

    DB:2.81:Custom Defaulttreecellrender Not Rending Node Labels Correctly. 7m

    Ok, seems I need to add this.panel.invalidate(); to the node render after chaning the icon.

    Also changing the layout manager attached to the panel (without adding a invalidate) will help the problem.

  • RELEVANCY SCORE 2.81

    DB:2.81:Double Click On Jtree 9m


    How can I get double click event on leaf node of JTree ?

    Thanks in advance.

    DB:2.81:Double Click On Jtree 9m

    Try the nice convenient "Search Forum" box on the left side of the Forum home page: a search for "JTree double click" gives you the answer at
    http://forums.java.sun.com/thread.jsp?forum=57thread=119292

  • RELEVANCY SCORE 2.81

    DB:2.81:Getting Back The Jtree Instance ps


    Hi:

    I have an instance of a node (DefaultMutableTreeNode) that was copied from a JTree and pasted in the system clip board. In another part of the application I retrieve the node. Now based on the node is it possible to get a reference back to the original JTree?

    DB:2.81:Getting Back The Jtree Instance ps

    I doubt it since a TreeNode is part of the model, not part of the UI. The UI has a handle to the model, but not vice versa.

  • RELEVANCY SCORE 2.81

    DB:2.81:Jtree Behaviour p8


    Hi guys;

    i want to implement the next behaviour for a Jtree:

    suppose that my JTree is filled with nodes like: colors, sports ...and their leafs also...
    when i click a node or leaf i want to be able to get the value of the selected node: ( i.e here: colors or sports..)

    do i have to add a Listener to my JTree? how can i then do this job?

    thanks for help!

    DB:2.81:Jtree Behaviour p8

    That's on the very first page of the tutorial.

    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • RELEVANCY SCORE 2.80

    DB:2.80:Jtree Node Info s7


    Hi there all,
    I am making a swing application using jtree and i have a problem faced.
    I need some help.
    I create a default node

    final Object bookId=me.getKey();
    inal Object bookName=me.getValue();
    DefaultMutableTreeNode book = new DefaultMutableTreeNode(here??);

    i have a treemap and in this there is an id and a name list.
    what i want to do,
    when i click to a node in a tree i want to get both name and id for this node. but i couldnt.
    How can i put bot name and id in the nodes? Names will be nodes name?
    thanks.

  • RELEVANCY SCORE 2.80

    DB:2.80:Urgent---- Node Selection In Jtree m8


    Can I select a treenode programmatically without triggering a TreeEvent even though I have added TreeSelectionListener to JTree.
    When I use setSelectionPath to select a node , it is triggering an event .
    How do I stop this??

    Thanks in advance

    DB:2.80:Urgent---- Node Selection In Jtree m8

    Can I select a treenode programmatically without
    triggering a TreeEvent even though I have added
    TreeSelectionListener to JTree.
    When I use setSelectionPath to select a node , it is
    triggering an event .
    How do I stop this??

    Thanks in advanceHi Joshi! ,

    All u have to do is call the
    tree.removeActionListener(myActionListener);
    tree.setSelectionPath(..);
    //after your done with this
    tree.addActionlistener(myActionListener);

  • RELEVANCY SCORE 2.80

    DB:2.80:Jtree Node Selection - Urgent fm


    I posted this message earlier but may be I think it was not clear for the people to answer. I try to put this question in more in more accurate way.

    Question : How can I modify JTree so that the selection of the node(JLabel) can be made to expand to the width of the JTree?

    BR,
    Maulin

    DB:2.80:Jtree Node Selection - Urgent fm

    I guess its not too difficult, just write your own tree renderer, set renderer's(JLabel) width accoriding to tree's width when selected.

  • RELEVANCY SCORE 2.80

    DB:2.80:Dynamic Jtree 79


    I'm trying to replace a JList with a JTree. I want to be able to load objects from a database. These objects are currently shown in a list, but I'd like to add a 'group' field to each object which is a text representation of the node that object appears in. I want to be able to first load foo the groups from a list, then go through all of the objects, and insert them into the node whose name matches the 'group' field. I've been trying this all day and it's really giving me a headache.

    I can't get my head around how to select a node once it's been added. Ideally Java would offer a method to add a child node to an existing node with a specified name. Is this possible, with a collection or otherwise?

    Many Thanks

    DB:2.80:Dynamic Jtree 79

    Sorry to keep posting huge snippets, but this is a working version, demonstrating the problem. The more times you click the button, the more times the items are duplicated.

    Thanks for any help/insight
    I think the problem stemmed frm the fact that at each 'Group' (Branch) node, I was adding the node itself using new DefaultMutableTreeNode(name), where name was a string, what I needed was new DefaultMutableTreeNode(group) where group was an object of type Group.

    Thanks for the input.

    Edited by: Echilon on Jan 7, 2008 4:54 AM
    Problems solved.

  • RELEVANCY SCORE 2.80

    DB:2.80:Reloading Jtree And Expanding Last Selected Rows 81


    I'm working on an applet that loads the nodes of a JTree from a database. When a node is selected, its data are displayed in a different panel. When a "reload" button is clicked, all the nodes in the JTree are removed except for the root node, and the JTree is recreated from the database. I'm try to get the new JTree to expand and select the rows that were selected before reloading, but I can't get this to work.

    Before removing the nodes, I save the currently selected row numbers using JTree.getSelectionRows(). After recreating the JTree, I re-select the previously selected rows and try to expand them:

    // tree is the name of the JTree.
    tree.setSelectionRows(selected);
    for (int i= 0; i Array.getLength(selected); i++) {
    System.out.println("selected row: " + selected);
    tree.scrollRowToVisible(selected[i]);
    }
    tree.updateUI();

    The previously selected rows do not automatically become visible in the resulting JTree. I also tried using tree.expandRow instead of scrollRowToVisible, with the same results.

    Any help would be appreciated!

    DB:2.80:Reloading Jtree And Expanding Last Selected Rows 81

    Hi,

    I've read through this thread in search for finding a way to update and preserve my JTree, however the solutions at the end does not work for me.

    See, this is my problem:
    Tree
    |----N 0.0.0
    | |- N 0.1.0
    | |- N 0.2.0
    | |- [N 0.2.1]
    |----N 1.0.0
    |- N 1.1.0
    |- [N 0.2.1]
    Yes, I've got TreeNodes drawn at more than one place, so .getParent() will not work, hence getting the path to the node does not work either.

    I would like to be able to use this function listed here. it works fine except it fails when there are nodes with different childCount than on save. (ps. the function I want is the one first posted by jds@ku.edu)
    I could solve this if there is any way to get the TreeNode-object represented by the rowIndex, is there any way to do this?

    And changing the treestructure to not use the same object twice or more is not an option cause of other functionalities of the program.

    //Regards, me

    Edited by: ShadowRoze on Sep 6, 2008 12:29 PM

  • RELEVANCY SCORE 2.79

    DB:2.79:Jtree Node Expansion 18


    I created a JTree root with its children nodes. Initially it is closed. I created a text field in the container. The matter is: If I write a node name inside the textfield, the pardicular node whether it is a leaf node or any node should be expanded with its parents.
    Is it possible? (with text listener or focus listener.)if so, kindly suggest the solution.

    DB:2.79:Jtree Node Expansion 18

    Dear doopsterus,

    you r saying about whole tree expansion. I want that particular node written in the text field.

    Then next what?

  • RELEVANCY SCORE 2.79

    DB:2.79:How To Reach At A Node Of Jtree : Urgent xa


    Hay all,
    Plz tell me that how to reach at a particular node in a JTree, whose name is known to you.I have used a DefaultTreeModel to create a tree. As

    deviceTreeModel=new DefaultTreeModel(rootNode);
    tree = new JTree( deviceTreeModel );

    Thanks and Regards,
    Sharad Agarwal

    DB:2.79:How To Reach At A Node Of Jtree : Urgent xa

    Dr Clap:

    i like your solution (and faster)
    it's much better than traversing the tree O(1) vs O(n)
    a big performance improvement if the tree contains many nodes

    also, the code would be much cleaner and easier to read.

  • RELEVANCY SCORE 2.79

    DB:2.79:Changing Color In A Jtree Node ps


    Hi,
    I am trying to change text color in a node of a JTree. I can get the node to change one color but I am having trouble getting it to change multiple colors. Here is an example:
    Name: John Smith
    In this example, "Name:" I want to be white and "John Smith" I want to be yellow. Both appear in one node of a tree.
    I can wrap the "Name:" in HTML tags but when the node updates there is a flickering during the redraw that is only visible on a dual processor or hyperthreaded machine.
    Does anyone have any ideas?

    Thanks!!

    DB:2.79:Changing Color In A Jtree Node ps

    Great question Ejuricek, i also needed that answer. Thanks!

    Message was edited by:
    kcenturion

  • RELEVANCY SCORE 2.79

    DB:2.79:Jtree 7a


    Each node in my JTree has several attributes which I now want to get at. I can get the selected path for my tree using
    getSelectionPath(), but I don't seem to be able to get at the node itself

    DB:2.79:Jtree 7a

    Hi,
    please use vector for your purpose and put all nodes in a vector and you try to get from collection.

    1) DefaultMutableTreeNode currentNode =(DefaultMutableTreeNode)Tree.getLastSelectedPathComponent();

    2) CustomNodeType currentItem = (CustomNodeType)currentNode.getUserObject();

    This shows how would you cast it to your custom node type.
    I hope this will help you out.
    Regards,
    Tirumalarao
    Developer Technical Support,
    Sun Microsystems,
    http://www.sun.com/developers/support.

  • RELEVANCY SCORE 2.78

    DB:2.78:Finding The Position Of A Node In A Jtree ap


    Hi all,
    I have to implement search functionality in a JTree.
    Now there are two modes of searching
    1. Search Tree upwards (from the selected node)
    2. Search the tree Downwards(from the selected node)

    The procedure is as follows:
    1.Select the Tree node.
    2. Press Ctrl +F
    3. a Search Dialog appears where in by default, the node name is prepopulated in the text field of the dialog Box.
    4.Now Press Find .
    This should find the next occurance of the Node which is being mentioned in the search field in the dialog box.
    Implementation
    Now what i have done it,when the user clicks Find button it will find all the occurances of the node from the root of the JTree and stores it in a List.Now i want to search for the next matching occurance of the node.The problem is that i do not get the position of the node being selected in the JTree .Also if we change the search Field to search some other field (upwards or downwards from the seleced position) i dunno where to start from?
    Can anyone guide me along????

    Best Regards
    Ashish

    DB:2.78:Finding The Position Of A Node In A Jtree ap

    But you have to be aware that the "row" in a tree is based only on the visible rows. The nodes hidden by the parent node being collapsed do not get counted for rows. But doing a search is not something usually done just on visible rows.

  • RELEVANCY SCORE 2.78

    DB:2.78:How To Get Correct Node In Jtree With Discontiguous_Tree_Selection Mode? k9


    The following code creats a JTree with DISCONTIGUOUS_TREE_SELECTION mode. When select a single node, the node's name is printed correctly as expected. However, in Window environment, after select one node, if holding the ctrl key and select a different node, the program still prints out the name of the first selected node although both nodes are highlighted. Can some one tell me how to get the name of the second (i.e. the last) selected node printed?
    Thank you very much!

    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.io.*;

    public class TestTree extends JFrame {
    JTree tree;
    public TestTree() {
    super();
    setBounds(0,0,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    tree = new JTree();
    getContentPane().add(tree);
    TreeSelectionModel model = new DefaultTreeSelectionModel();
    model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setSelectionModel(model);
    tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    Object obj = tree.getLastSelectedPathComponent();
    System.out.println(obj.toString());
    }
    });

    }

    public static void main(String [] args) {
    TestTree test = new TestTree();
    test.show();
    }
    }

  • RELEVANCY SCORE 2.78

    DB:2.78:How To Expand Jtree Using Node Path. ap


    How to expand jtree using node path.

    DB:2.78:How To Expand Jtree Using Node Path. ap

    Convert your node path to a TreePath and call expandPath.

  • RELEVANCY SCORE 2.78

    DB:2.78:How To Select A Node In A Jtree By Name c9


    I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help

    Thanks!

    DB:2.78:How To Select A Node In A Jtree By Name c9

    Nevermind. Found the answer:

    http://forum.java.sun.com/thread.jsp?forum=31thread=286390

  • RELEVANCY SCORE 2.77

    DB:2.77:Xml In Jtree: How To Not Collpase Jtree Node, When Renaming Xml Node. 81


    Hi.

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

    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?

    Thanks in advance.

    DB:2.77:Xml In Jtree: How To Not Collpase Jtree Node, When Renaming Xml Node. 81

    Thank you for your answer.

    Actually, I supposed, that there can be some method in Xerces for changing node's name. But it seems, there is not.

    Rewriting functionality of xml tree in own classes seems to be not "natural", because DOM has almost everything, i need.

    May be my question is really not for this forum group.

  • RELEVANCY SCORE 2.77

    DB:2.77:Checkbox Treecellrenderer 1z


    Hi All,

    I have implemented the TreeCellRenderer, such that each node in
    my JTree has a checkbox and a label in a JPanel.

    Now I am creating a mouse listener for the tree. I can get the
    name of the node using TreePath.getLastPathComponent(). But how can
    I access the state of the checkbox in the selected node?

    Thanks,
    Cathy.

    DB:2.77:Checkbox Treecellrenderer 1z

    perhaps getting the treenodes component....something like that.

  • RELEVANCY SCORE 2.77

    DB:2.77:Jbutton(S ) To Navigate A Jtree zz


    Hi,

    I have a JTree representing a simple hierarchy. I also have four buttons to navigate through the tree (first , previous, next,last JButton(s))

    I want to implement the following functionality :

    if i click a given button the current selected node in JTree should be set accordinely to chosen button : ex if i click next button ; then JTree should select the node directly under current selected node ..and so for each button.

    can some one suggest some code to do that ?

    thanking you.

    DB:2.77:Jbutton(S ) To Navigate A Jtree zz

    Hi,

    I have a JTree representing a simple hierarchy. I also have four buttons to navigate through the tree (first , previous, next,last JButton(s))

    I want to implement the following functionality :

    if i click a given button the current selected node in JTree should be set accordinely to chosen button : ex if i click next button ; then JTree should select the node directly under current selected node ..and so for each button.

    can some one suggest some code to do that ?

    thanking you.

  • RELEVANCY SCORE 2.77

    DB:2.77:Custom Jtree Node dd


    Hi,

    can someone post an example of a JTree node, extending the Default Mutable Tree Node, including adding this node to a jtree?

    I try to figure this out ...

    thanks in advance,
    DickerTiger

    DB:2.77:Custom Jtree Node dd

    Dear
    This is example to add node to add root node.
    see and try this.

    import javax.swing.tree.*;
    import javax.swing.tree.TreePath.*;

    public DefaultMutableTreeNode Root=new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode ParameterNode=new DefaultMutableTreeNode("Parameter");
    Root.add(ParameterNode);

    yours
    Shripad
    Contact at shripadoka@hotmail.com

  • RELEVANCY SCORE 2.77

    DB:2.77:Jtree And To Remove A Node??? z1


    Hi,

    I would like to know how I can remove a specific node, by his name? The name that is displayed on the JTree. For instance, I want to remove all the node that they have the name "example".

    Thanks

    DB:2.77:Jtree And To Remove A Node??? z1

    In fact, I use the model DefaultMutableTreeNode. And I would like to remove all the child node.

  • RELEVANCY SCORE 2.77

    DB:2.77:Simple Jtree Problem j1


    I have got the name of the node of a tree alongwith its path.I need to highlight it.(hightlight will select that node in the tree)

    which method shall I use?

  • RELEVANCY SCORE 2.76

    DB:2.76:Help To Get A Treepath From Jtree 3c


    Hi

    I am building an application in which I require a treepath of the particular node in the Jtree. i.e Suppose I have a jtree in which node (say ?test?) is present.

    Now I want treepath from root of my jtree to that particular node(i.e test.)

    One imp thing is that I can't use getSelectionPath() here because user is not selecting that particular node.
    But some other function is just passing the node
    object to my class.
    So I can not use getRowForLocation( int x ,int y) also.

    So the function Should be like this

    Public TreePath getTreepath( JTree tree , Node node)

    {

    // Please Tell me what to write here?????????

    }

    DB:2.76:Help To Get A Treepath From Jtree 3c

    hi hrishig,

    thanks a lot for ur code segment...
    i was searching exactly for the same kind of code...
    thanks a lot once again..

    bye
    satish

  • RELEVANCY SCORE 2.76

    DB:2.76:Getting The Coordinates Of A Selected Node Of A Jtree a1


    Hello,

    How can I get the co-ordinates of a currently selected node of a JTree,
    if the node is selected using setSelectionPath() method on a KeyPress event?

    Thank you.

    DB:2.76:Getting The Coordinates Of A Selected Node Of A Jtree a1

    I believe your answer is in this thread:

    http://forum.java.sun.com/thread.jspa?threadID=699159

    Looking through the API, getPathBounds(...) or getRowBounds(...) sounds promising.

  • RELEVANCY SCORE 2.76

    DB:2.76:Jtree Node Refuses To Collapse Upon Clicking Handle; Makevisible() Was Used mj


    Hello,
    While creating a new node and inserting as a leaf in the JTree, I use tree.makeVisible(newTreePath) to expand the new node and make visible. (Using expandPath() will not expand if a leaf was added).
    However now the jtree node refuses to collapse upon clicking the node handle.
    How do I get it to not insist on staying open - be able to collapse manually?

    thanks,
    Anil

    DB:2.76:Jtree Node Refuses To Collapse Upon Clicking Handle; Makevisible() Was Used mj

    Hello,
    While creating a new node and inserting as a leaf in the JTree, I use tree.makeVisible(newTreePath) to expand the new node and make visible. (Using expandPath() will not expand if a leaf was added).
    However now the jtree node refuses to collapse upon clicking the node handle.
    How do I get it to not insist on staying open - be able to collapse manually?

    thanks,
    Anil

  • RELEVANCY SCORE 2.76

    DB:2.76:Problem With Jtree 3z


    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    DB:2.76:Problem With Jtree 3z

    Thanx a lot Levi, your searchAndExapand(...) and search(...) are the ones which helped me a lot.

    Best Regards,
    Debopam.

  • RELEVANCY SCORE 2.74

    DB:2.74:How To Separate Different Nodes On A Jtree With Same Name. zc


    I have a JTree built by adding DefaultMutableTreeNode nodes on the root node. I want to differentiate the nodes with the same name: when I call the getUserObject method of each selected node, I get its corresponding value from a hashtable with the name as a key. But nodes with the same name don't get the right value, cause they have the same key! I tried to put a field on an extended class of DefaultMutableTreeNode, but, of course, when I do (DefaultMutableTreeNode) selectedTreePath.getLastPathComponent() the field is instantiated with the default value, not the right one. Any ideas;

  • RELEVANCY SCORE 2.74

    DB:2.74:Rootless Jtree (Urgent!!!) pa


    Hi! I am trying to create a Jtree with no root nodes, Instead It will have many nodes at the top level. Like this.

    X1
    |_ child
    X2
    |_ child
    X3
    |_ child

    etc, you get the point.

    I have done this by using a Vector of nodes. Here is my sample program,

    My Tree node class
    _____________________
    public class ISTreeNode extends DefaultMutableTreeNode {
    private Icon icon;
    private String id;
    private String type;
    .....
    }

    My node Renderer
    _______________________________

    public class ISTreeNodeRenderer extends DefaultTreeCellRenderer {

    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel, boolean expanded, boolean leaf,
    int row, boolean hasFocus)
    {
    ISTreeNode node = (ISTreeNode)value;
    .....
    ...... set the icon/ type etc
    .....
    }
    }

    my tree creation procedure
    _______________________________

    initData() {
    Vector nodeVec = new Vector(3);
    for (int i=0; i 3; i++) {
    String vpdStr = "X "+i;
    ISTreeNode vpd = new ISTreeNode(vpdStr);
    vpd.setIcon(getIcon());
    vpd.setId(""+i);
    vpd.setType(ISViewerConstants.VPD);
    nodeVec.addElement(vpd);
    }
    JTree tree = new JTree( nodeVec );

    }

    tree.setCellRenderer(new ISTreeNodeRenderer());

    _____________________________________

    Well so that was sample program. But i have a problem to get to my ISTreeNOde in my cellRenderer, at
    ISTreeNode node = (ISTreeNode)value; code in renderer. JVM gives a wrong Cast exception. Is there some thing i am doing wrong. How do i get the ISTreeNode, in renderer cos i want to set the icons etc. Or is there a better way to create a Jtree with multiple roots and custom icons. How do i create child nodes if i am using a vector data model.

    Appreciate your help its urgent.
    Sada

    DB:2.74:Rootless Jtree (Urgent!!!) pa

    That last response wasn't in answer to your latest response, but to the one before :-)

  • RELEVANCY SCORE 2.74

    DB:2.74:Problem In Jtree pz


    Hello,

    I am creating a JTree and trying to find the depth of a selected node;So I am trying to find the selected node and then get the depth.I am getting it correctly,but after I find it ,tree collapses to root and does not exapnd on clicking.Let me know the error.

    import java.awt.Dimension;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;

    public class treeTest extends JFrame{
    JTree _tree;
    public treeTest() {
    _tree=new JTree();
    _tree.setPreferredSize(new Dimension(200, 600));
    _tree.addMouseListener(new MouseListener() {

    public void mouseClicked(MouseEvent e) {
    String ssname;
    int depth;
    if (e.getSource() instanceof JTree) {
    try {
    ssname = _tree.getSelectionPath()
    .getLastPathComponent().toString();
    DefaultMutableTreeNode node=(DefaultMutableTreeNode)find(_tree,
    (DefaultMutableTreeNode)_tree.getModel().getRoot(),ssname);
    depth=node.getDepth();
    } catch (Exception exp) {
    ssname = "novalue";
    depth=0;
    //_repSel.removeAllItems();

    }
    if (!(ssname.equals("novalue"))) {
    //Vector v = getComboData(ssname);
    DefaultMutableTreeNode node;
    node=find(_tree,(DefaultMutableTreeNode)_tree.getModel().getRoot(),ssname);
    depth=node.getDepth();
    System.out.println("depth is:"+depth+"for node:"+node);

    }

    }

    }
    public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

    }

    public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

    }

    public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

    }

    public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

    }

    });
    getContentPane().add(_tree);
    pack();
    setVisible(true);
    }
    public static void main(String args[]){
    new treeTest();
    }
    public DefaultMutableTreeNode find(JTree _tree,
    DefaultMutableTreeNode root, String name) {

    if (root.getUserObject().equals(name)) {
    _tree.collapseRow(0);
    return root;
    }
    DefaultMutableTreeNode el = null;
    int childCount = root.getChildCount();
    DefaultMutableTreeNode child;
    for (int i = 0; i childCount; i++) {
    child = (DefaultMutableTreeNode) root.getChildAt(i);
    el = find(_tree, child, name);
    if (el != null)
    return el;
    }
    return el;
    }

    }

    DB:2.74:Problem In Jtree pz

    Hello everybody,

    I got the answer. I can use :
    DefaultMutableTreeNode node=(DefaultMutableTreeNode)_tree.getSelectionPath().getLastPathComponent();
    to get the selected node.I am sorry to post the question.

    Sruthi.

  • RELEVANCY SCORE 2.74

    DB:2.74:Get A Certain Node Of A Jtree 7z


    Hi to all!

    I' m using JTree combined with DefaultMutableTreeNode and DefaultTreeModel.
    My problem is that I have the path of a certain node and I just want to get a certain node of this path in order to edit (or better to update) its "userObject".
    Maybe it's a silly question but I'm new to JTree and I feel a little lost with all these methods provided.

    Thank you in advance.

    DB:2.74:Get A Certain Node Of A Jtree 7z

    Hi to all!

    I' m using JTree combined with DefaultMutableTreeNode and DefaultTreeModel.
    My problem is that I have the path of a certain node and I just want to get a certain node of this path in order to edit (or better to update) its "userObject".
    Maybe it's a silly question but I'm new to JTree and I feel a little lost with all these methods provided.

    Thank you in advance.

  • RELEVANCY SCORE 2.74

    DB:2.74:Jtree Cell Width 8z


    Hiya

    I'm trying to make my jtree's cell width be equal to the width of the entire JTree it is in so that when selected, a highlight bar stretches across the entire jtree rather than just around the text of that node?
    I've created a DefaultTreeCellRenderer and attached it to the jtree, and tried overriding the getWidth, getPreferredSize, getBounds, but I can't get it working.

    How can I do this?
    Thanks

    DB:2.74:Jtree Cell Width 8z

    Ah that's nice. Very simple. If I can't get mine working properly I may use this. Very nice work, thanks

  • RELEVANCY SCORE 2.73

    DB:2.73:How To Edit A Jtree Node Programatically. s7


    How to edit a JTree Node programatically.

    DB:2.73:How To Edit A Jtree Node Programatically. s7

    For example

    I got this tree.
    Parent
    - child
    - another
    - also another.

    This is a part of my object inspector in which there are two ways to edit the entities either by the tree nodes or by the visual objects itself.
    If i change the caption of one of my node in the other way. I should reflect it in a tree.(programatically of course no need to type.)

  • RELEVANCY SCORE 2.73

    DB:2.73:Find The Node That Mouse Is Over In Jtree sj


    I am trying to find which specific node the mouse is over when moving in a JTree but I havent succeeded.

    From my event variable I get access to the methods getX()/getY() (or getLocation()). And I have seen some methods in JTree where you can input the x/y values to get a row(int). Also some method/s where you can input this row value to get a Path. But when I print this path it doesnt agree to the node I am over.

    Any other way to acheive this?

    Message was edited by:
    sandsater

    DB:2.73:Find The Node That Mouse Is Over In Jtree sj

    I understand exactly what you are saying. You don't understand what I am asking.

    The point is you didn't post any executable code, so we can't confirm that what you are saying is in fact true. You may have made a silly programming mistake somewhere that is causing the problem. 99% of the problems posted in the forum are silly mistakes. Thats why I always ask for an SSCCE so I can verify whats happening. It only takes 5 minutes to create one if you truly understand the problem as well as you think you do. Or maybe the problem could be a platform or version problem. The only was to verify this is to run some executable code.

    Anyway try looking at the SwingUtilities class, it has methods for converting MouseEvents and Points to different coordinates.

  • RELEVANCY SCORE 2.73

    DB:2.73:Determining The Current Selected Node In A Jtree 73


    Case 1:
    I cannot get the current selected node when I expand or collapse a node (Press on the plus or minus icon)

    Case 2:
    I can only get the currently selected node by clicking on the node name itself.

    I want to be able to get the currently selected node for both cases. Below is my code.

    tree.addTreeWillExpandListener( new TreeWillExpandListener()
    {
    public void treeWillExpand( TreeExpansionEvent event )
    {
    TreePath currentSelection = tree.getSelectionPath();
    if ( currentSelection != null )
    {
    DefaultMutableTreeNode currentNode =
    ( DefaultMutableTreeNode ) currentSelection.getLastPathComponent();
    System.out.println( "Current Selected Node is: " + currentNode );
    }
    else
    {
    System.out.println( "Nothing selected" ); // I GET HERE WHEN CLICKING PLUS OR MINUS ICON
    }
    }

    public void treeWillCollapse( TreeExpansionEvent event )
    {
    }
    });

    DB:2.73:Determining The Current Selected Node In A Jtree 73

    Ok, I think I got it figured out. Here's the code for whoever is interested.

    private final static MyNode eDummyNode = new MyNode( "dummy" );
    ...
    tree.addTreeWillExpandListener( new TreeWillExpandListener()
    {
    public void treeWillExpand( TreeExpansionEvent event )
    {
    TreePath path = event.getPath();
    if (path != null)
    {
    DefaultMutableTreeNode currentNode = ( DefaultMutableTreeNode ) path.getLastPathComponent();
    DefaultMutableTreeNode kid = (DefaultMutableTreeNode)currentNode.getChildAt(0);
    if (kid.getUserObject().equals(eDummyNode))
    {
    tree.setSelectionPath( new TreePath( currentNode.getPath() ) );
    populateNode();
    tree.makeVisible( new TreePath( ((DefaultMutableTreeNode)currentNode.getChildAt(0)).getPath() ));
    }
    }
    }

    public void treeWillCollapse( TreeExpansionEvent event )
    {
    ((DefaultMutableTreeNode)(event.getPath().getLastPathComponent())).removeAllChildren();
    ((DefaultMutableTreeNode)(event.getPath().getLastPathComponent())).add(new DefaultMutableTreeNode( eDummyNode));
    }
    } );

  • RELEVANCY SCORE 2.73

    DB:2.73:Urgent Jtree Event f9


    I have a JTree constructed.Added it to left side of JSplitPane.
    Also added listeners to JTree to handle event on node selection . So on selection on a node I add a JPanel to right side of JSplitPane.
    Problem I am facing is SOMETIMES INSPITE of selecting the NODE, the event is not trigggered.So I need to select the node once again and then the event is triggered.This is not consistent problem either.
    Please someone help me fixing this.
    Thanks in advance.

    DB:2.73:Urgent Jtree Event f9

    Can u send me sample code plz.....

  • RELEVANCY SCORE 2.73

    DB:2.73:Traversing Jtree Urgent Please Help a3


    Hai all

    i have a window where user creates his own tree with JTree using [New node,Modify,Delete node] Button.

    after his createion user clicks ok.

    here i want to read the structure of the JTree so that i can do my respective work .

    please anyone tell me how to read the whole tree hierarchical structure.

    Thankyou
    Rajesh

    DB:2.73:Traversing Jtree Urgent Please Help a3

    i have a JTree made up of DefaultMutableTreeNodes. To go through all the nodes of the tree, I use one of the enumeration methods of the root DefaultMutableTreeNode. e.g.
    Enumeration e = rootNode.postorderEnumeration();
    DefaultMutableTreeNode dmtn;
    while (e.hasMoreElements()) {
    dmtn = (DefaultMutableTreeNode)e.nextElement();
    //do some stuff with the current node
    }there are a number of enumeration methods which traverse the nodes in different directions.
    HTH
    anorakgirl

  • RELEVANCY SCORE 2.73

    DB:2.73:Insert Node In Jtree sj


    Hi!

    I have a JTree created and I need to insert a node in the JTree at a particular path that the use wants. I read the path and the node to be added as a string from the user:

    //Read path and node name
    String path = JOptionPane.showInputDialog (this, "Enter new node path");
    File f = new File (path);

    //Create new child
    DefaultMutableTreeNode child = new DefaultMutableTreeNode (f.getName());
    DefaultMutableTreeNode parent = new DefaultMutableTreeNode (f.getParent());

    //Get model and add new node
    DefaultTreeModel model = (DefaultTreeModel)jTree1.getModel();
    model.insertNodeInto (child, parent, parent.getChildCount());
    child.setParent(parent);
    jTree1.scrollPathToVisible(new TreePath(child.getPath()));
    model.reload();

    But, the new node is not showing up.

    Kindly help,

    x86

    DB:2.73:Insert Node In Jtree sj

    try this method

    /**
    * addNewNode inserts newChild at location index in parents children.
    *
    * @param newItem
    */
    public void addNewNode(String newItem) {
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newItem);
    TreePath selectionPath = tree.getSelectionPath();
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
    selectionPath.getLastPathComponent();
    ( (DefaultTreeModel) tree.getModel()).insertNodeInto(newNode,
    selectedNode, selectedNode.getChildCount()); ;
    }

  • RELEVANCY SCORE 2.73

    DB:2.73:Display A Xml File On Jtree Problem (Validation Of Xml File) j8


    I am now creating a JTree which displays XML file while I am now using
    xerces-J 1.4.4. in my JTree, the user can add the node or remove the node of the JTree. However, I want to check whether the change on the JTree can be

    I want that right click on a node of JTree will display a popup menu.
    This menu has the name of the node which allows to be added. However,
    how can I check whether the change of the JTree is valid? for example, in the add case of element to JTree, I want to check whether the new node allows to be added in that place.

    Thanks!

    DB:2.73:Display A Xml File On Jtree Problem (Validation Of Xml File) j8

    xerces can help the validation! I just don't know how to use xerces for this problem...

  • RELEVANCY SCORE 2.73

    DB:2.73:Jtree Question 81


    hi there.say i select a node in a jtree by clicking on it.say the name of the node is node1 and i want to insert a node, just before this node.lets call it node0.if I get the index of node1 which say is 6.im using a defaulttreemodel.will the method
    dtreeModel.insertNodeInto(new DefaultMutableTreeNode("node0"), node, indexOfNode1);insert the node node0 before node1?thanks

  • RELEVANCY SCORE 2.73

    DB:2.73:Jtree - Node Name Problem 9c


    Hi

    I have a problem with a JTree. When I add a new node, the node name sometimes does not appear fully i.e. Node N..., even though there is more than adequate room for the name. Is there anyway of overwritng the insertion of the dots?

    Any suggestions appreciated

    Bernie-wolf

    DB:2.73:Jtree - Node Name Problem 9c

    I also have the same problem. I my case my tree nodes are refreshed by a thread every 10 seconds, however after every refresh cycle at least one of the nodes do not retain their full text labels.

    As for the refresh operation, I update/add/delete nodes from a DefaultTreeModel and subsequently call nodeChanges(...) nodeStructureChanged(..) at the end of the this cycle to upadate the view.
    The updation occurs inside a method which is thread-safe.