File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes JTree - programmatically control adding nodes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTree - programmatically control adding nodes" Watch "JTree - programmatically control adding nodes" New topic

JTree - programmatically control adding nodes

Kemal Sokolovic

Joined: Jun 19, 2010
Posts: 825

I have read meny tutorials and crossed almost all examples in "Core Java 2 Vol 2", "Java Swing 2nd edition" and some others, but I couldn't find the solution for this:

I have a JTree looking something like this:

Student Groups
    Group 1
        Student 1
        Student 2
        Student n
    Group 2
        Student 1
        Student 2
        Student m

Is there any way to achieve following:
1) Add a new Student Group (let's say, Group 3) without selecting parent node Student Groups?
2) Add a new Student (let's say, Student m+1) in Group 2 without selecting parent node Group 2?
My plan was to achieve this by clicking on a proper menu item (New -> Student Group, New -> Student). After entering data in New Group/New Student dialogs (for new student, I would have Combo Box from which I would select group to add into), group/student is added in proper data structure, and tree view is refreshed displaying new items.

The quieter you are, the more you are able to hear.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10825

Your plan sounds logical enough. What is the problem?
I hope you do realize you are just moving away the functionality from right click to the menu which is also translating to more operations for the user. What exactly are you trying to achieve here? Any specific reason to avoid the right clicks?

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Kemal Sokolovic

Joined: Jun 19, 2010
Posts: 825

With right click I automatically select the parent to add a node to. I will probably add that option too, via popup menu.
But, with the approach I am trying to achieve, when I add a new Student, I don't actually have selected parent in the tree. Instead, user will be able to choose parent (Group #) in the dialog where he enters student information.
My problem is, how can I then use the information of the parent user selected in dialog, to add a new node to the tree?

For example:
In the tree, Group 1 or some other node can be selected. But when New -> Student dialog is shown, user can choose to add a student to Group 2, which is not selected.

I hope I made myself clear.
I agree. Here's the link:
subject: JTree - programmatically control adding nodes
It's not a secret anymore!