Search code examples
javaswingnetbeanspathjtree

jtree, Is there a way to convert the tree selected path to a string and back?


I have this Jtree, and I have to insert into it "tables" in my tbltables table. (What I mean by that is I have a table in my MSQL database called tbltables, and in it there's a list of tables).

So those tables can have tables in them as well. So now the problem: I don't know how to tell it that the one table should be in the other one. The only thing I can think of, is when I add the tables to my Jtree (I can do that, but then not save how they look into my db), I can then save the selected index, or added node's destination. like ["Groceries","fruit"] and then when I call it from my database I can add it like that.

So then I will need to convert the path to a string and vice versa. Am I doing this wrong? Is there better way to do this?

Note: I'm not working with physical files and folders, I'm working with "imaginary ones" in my database of which I have their destination.


Solution

  • I would say your table should have primary key (let's name it table_id) and a foreign key parent_table_id referencing the primary key. The parent id could be null (e.g. for root).

    You can define class MyTableNode with id, parent id and name fields. Build your TreeModel based on the MyTableNode hierarchy. DefaultMutableTreeNode can keep any user object.

    Then your can define own renderer for the JTree to show name text of the user objects (MyTableNodes ) or try to override toString() method of the object which is used to show value in default renderer.

    Your way (storing paths as string) could also work. REpresent your node's TreePath as "root/first child/.../leaf". SO each table (row of the JTree) will have own path. Then restoring the tree node means parsing the path to String[] and navigating from the tree root finding appropriate child with the next name from the array.