JTreeTable / TreeModel question

Hi all,
I have two questions about JTrees and TreeModels.
I have an application which builds a TreeModel from an XML file, and displays it in a JTreeTable (see: http://java.sun.com/products/jfc/tsc/articles/treetable1/). There are two panels to display an XML file. The XML file consists of parameters which all have a name and a value:
root
|- header
|  |- parameter1                value
|  |- parameter2                value
|  |- parameter3                value
|- data
   |- parameter1                value
   |   |- parameter1.1          value
   |   |- parameter1.2          value
   |- parameter2                value
   |   |- parameter2.1          value
   |- parameter3                value
   |- parameter4                valueNow I want to compare two nodes (one from both panels). The user can select a node on both panels to compare.
There are two tasks I want to implement:
1) I want to compare the parameters without taking into account the order in which they appear. A parameter is considered different when it has the same parent, the same name, but a different value.
2) I also want to separate those parameters which are unique for both trees (it doesn't appear in the other tree)
Thus, if I want to compare a node from jtree1, I first need to find a corresponding node in jtree2. If I can't find it, it is unique in jtree1, else I can compare the values and decide if they are the same. But how can I check for the corresponding node in jtree2?
There is also a second problem, how can I get the selected node from a JTreeTable? I tried with getSelectedIndex(), but when parameter1.1 is selected, the getSelectedIndex returns 7, while the root lement only has two child nodes... so getChildAt(index) will not work.

You can accomplish what you are looking to do through the use of something called model filtering. I have published an article on it on IBM's website at http://www-106.ibm.com/developerworks/library/j-filters/?dwzone=java.
I would direct you to the part that discusses 'exclusion filters' in particular. If you want to adapt this to the TreeModel architecture, it should be fairly simple.
Mitch Goldstein
Author, Hardcore JFC (Cambridge Univ Press)
[email protected]

Similar Messages

  • Lazy TreeModel questions...

    I'm considering a TreeModel that lazily instantiates its data when required.
    Essentially it won't bother loading data for a node until getChildCount is called for that node. This works alright - getChildCount doesn't get called until the nodes are expanded in the view.
    However, I would also like the data to be refreshed when a node is closed and expanded again. One way would be to discard the data when the node is collapsed. Another way could be to rebuild the data on the treeExpanded event. The latter seems dangerous - firing a nodeStructureChanged on the node that has just expanded will cause it to close again! That just leaves discarding the data when the node is collapsed; easy.
    The problem comes from getChildCount being called on some nodes that are not open but which have previously been opened. This leads to the model reloading the data for nodes that are not open in the view.
    Has someone got a more comprehensive idea of when getChildCount will be called by a JTree?
    I incorrectly assumed it would be only if the following were true:
    1. The node was expanded in that JTree
    2. isLeaf returns false
    Perhaps there's something more involved going on with the UI not trusting the isLeaf method?
    I'd appreciate any thoughts on a lazy TreeModel which might experience unnotified changes to the underlying data.
    Thanks in advance guys.

    It would appear that BasicTreeUI attempts to optimise its calls to getChildCount by trying to avoid calling until the node is expanded. However, once it's expanded a node it will happily continue calling getChildCount. Thus collapsing a node will still leave it thinking that it's safe to continue calling getChildCount to check whether an expand control is needed. Of course that's correct behaviour because the underlying model shouldn't have changed without firing an appropriate event.
    Firing a nodeStructureChanged event when the node closes, indicating to the tree that the underlying data has been discarded has sorted things out.
    Sorry for answering my own question!
    Still, if anyone's got any views on lazy tree models having written some of their own I'd be glad to hear them.

  • Cell alignment in JTreeTable

    hi,
    how can i set alignment of a cell in a JTreeTable?

    i have the following renderer :
    public class TreeTableCellRenderer extends JTree implements TableCellRenderer,SwingConstants
    protected int visibleRow;
    public TreeTableCellRenderer(TreeModel model) {
    super(model);
    public void setBounds(int x, int y, int w, int h) {
    super.setBounds(x, 0, w, JTreeTable.this.getHeight());
    public void paint(Graphics g) {
    g.translate(0, -visibleRow * getRowHeight());
    super.paint(g);
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    if(isSelected)
    setBackground(table.getSelectionBackground());
    else
    setBackground(table.getBackground());
    visibleRow = row;
    return this;

  • JTREE: Custom TreeModel does not update non-root nodes

    I have a JTree that uses a custom TreeModel that wraps over (delegates to) a data class X which keeps track of all its children. The class X maintains its own data structure internally (references to other data objects). It also implements 'equals' and 'hashcode' methods. When the data changes in X, it invokes fireTreeStructureChanged on the TreeModel. (There is a TreeModelListener registered with the TreeModel). This works very well for the root node but not for the other non-root nodes. The JTree correctly calls 'equals' and I can see that equals returns 'false' but for non-root nodes the JTree does not refresh though I can see the underlying data structure has changed.
    I am wondering if I may not have fully & correctly implemented fireTreeStructureChanged as it doesn't seem to do much. Or I may be looking at the wrong place. Any pointers would be appreciated.
    BTW, this question is very similar to one asked years earlier http://forums.sun.com/thread.jspa?threadID=153854 but it didn't help me :(
    Thanks.
    ps: working with jdk1.6.0_06 on WinXP.

    I have a same problem. I got an error "Cannot Update Libray".

  • Handle long-running EDT tasks (f.i. TreeModel searching)

    Note: this is a cross-post from SO
    http://stackoverflow.com/questions/9378232/handle-long-running-edt-tasks-f-i-treemodel-searching
    copied below, input highly appreciated :-)
    Cheers
    Jeanette
    Trigger is a recently re-detected SwingX issue (https://java.net/jira/browse/SWINGX-1233): support deep - that is under collapsed nodes as opposed to visible nodes only, which is the current behaviour - node searching.
    "Nichts leichter als das" with all my current exposure to SwingWorker: walk the TreeModel in the background thread and update the ui in process, like shown in a crude snippet below. Fest's EDT checker is happy enough, but then it only checks on repaint (which is nicely happening on the EDT here)
    Only ... strictly speaking, that background thread must be the EDT as it is accessing (by reading) the model. So, the questions are:
    - how to implement the search thread-correctly?
    - or can we live with that risk (heavily documented, of course)
    One possibility for a special case solution would be to have a second (cloned or otherwise "same"-made) model for searching and then find the corresponding matches in the "real" model. That doesn't play overly nicely with a general searching support, as that can't know anything about any particular model, that is can't create a clone even if it wanted. Plus it would have to apply all the view sorting/filtering (in future) ...
    // a crude worker (match hard-coded and directly coupled to the ui)
    public static class SearchWorker extends SwingWorker<Void, File> {
        private Enumeration enumer;
        private JXList list;
        private JXTree tree;
        public SearchWorker(Enumeration enumer, JXList list, JXTree tree) {
            this.enumer = enumer;
            this.list = list;
            this.tree = tree;
        @Override
        protected Void doInBackground() throws Exception {
            int count = 0;
            while (enumer.hasMoreElements()) {
                count++;
                File file = (File) enumer.nextElement();
                if (match(file)) {
                    publish(file);
                if (count > 100){
                    count = 0;
                    Thread.sleep(50);
            return null;
        @Override
        protected void process(List<File> chunks) {
            for (File file : chunks) {
                ((DefaultListModel) list.getModel()).addElement(file);
                TreePath path = createPathToRoot(file);
                tree.addSelectionPath(path);
                tree.scrollPathToVisible(path);
        private TreePath createPathToRoot(File file) {
            boolean result = false;
            List<File> path = new LinkedList<File>();
            while(!result && file != null) {
                result = file.equals(tree.getModel().getRoot());
                path.add(0, file);
                file = file.getParentFile();
            return new TreePath(path.toArray());
        private boolean match(File file) {
            return file.getName().startsWith("c");
    // its usage in terms of SwingX test support
    public void interactiveDeepSearch() {
        final FileSystemModel files = new FileSystemModel(new File("."));
        final JXTree tree = new JXTree(files);
        tree.setCellRenderer(new DefaultTreeRenderer(IconValues.FILE_ICON, StringValues.FILE_NAME));
        final JXList list = new JXList(new DefaultListModel());
        list.setCellRenderer(new DefaultListRenderer(StringValues.FILE_NAME));
        list.setVisibleRowCount(20);
        JXFrame frame = wrapWithScrollingInFrame(tree, "search files");
        frame.add(new JScrollPane(list), BorderLayout.SOUTH);
        Action traverse = new AbstractAction("worker") {
            @Override
            public void actionPerformed(ActionEvent e) {
                setEnabled(false);
                Enumeration fileEnum = new PreorderModelEnumeration(files);
                SwingWorker worker = new SearchWorker(fileEnum, list, tree);
                PropertyChangeListener l = new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            //T.imeOut("search end ");
                            setEnabled(true);
                            ((SwingWorker) evt.getSource()).removePropertyChangeListener(this);
                worker.addPropertyChangeListener(l);
                // T.imeOn("starting search ... ");
                worker.execute();
        addAction(frame, traverse);
        show(frame)
    }

    At the end of the day, it turned out that I asked the wrong question (or right question in a wrong context ;-): the "problem" arose by an assumed solution, the real task to solve is to support a hierarchical search algorithm (right now the AbstractSearchable is heavily skewed on linear search).
    Once that will solved, the next question might be how much a framework can do to support concrete hierarchical searchables. Given the variety of custom implementations of TreeModels, that's most probably possible only for the most simple.
    Some thoughts that came up in the discussions here and the other forums. In a concrete context, first measure if the traversal is slow: most in-memory models are lightning fast to traverse, nothing needs to be done except using the basic support.
    Only if the traversal is the bottleneck (as f.i. in the FileSystemModel implementations of SwingX) additional work is needed:
    - in a truly immutable and unmodifiable TreeModel we might get away with read-only access in a SwingWorker's background thread
    - the unmodifiable precondition is violated in lazy loading/deleting scenarios
    there might be a natural custom data structure which backs the model, which is effectively kind-of "detached" from the actual model which allows synchronization to that backing model (in both traversal and view model)
    - pass the actual search back to the database
    - use an wrapper on top of a given TreeModel which guarantees to access the underlying model on the EDT
    - "fake" background searching: actually do so in small-enough blocks on the EDT (f.i. in a Timer) so that the user doesn't notice any delay
    Whatever the technical option to a slow search, there's the same usability problem to solve: how to present the delay to the end user? And that's an entirely different story, probably even more context/requirement dependent :-)
    Thanks for all the valuable input!
    Jeanette

  • JTreeTable - Dynamic Child Loading - Selection problem

    Hi,
    I'm using JTreeTable Example 3 for my application.
    I've hidded the root and I am loading the child nodes for the second level nodes(parent) dynamically using the treeWillExpand() method . So my Model will be updated dynamically during runtime.
    The problem is, the selection of the TreeTable is not working properly after the expansion. Please throw some light on this issue.
    Thanks in advance
    Your
    Arun

    try to invoke reload(); on your treeModel ...
    i had this problem too only if the root is hided ...

  • Updating JTree Using a Custom TreeModel

    Hello,
    I have created a custom TreeModel that implements the TreeModel interface. The underlying data objects are stored in an existing tree structure similiar to a file/directory filesystem. When I add a new "file" object to the data model, I want to see it in the tree immediately. To make a long question short: what are the necessary steps to communicate with the JTree? Any info or references would be much appreciated.
    Thank You

    Thank you for your reply.
    Are you adding nodes or just expanding the JTree?Adding nodes (I also want to delete nodes)
    I don't know how to do this by just implementing
    TreeModel. This is using DefaultTreeModel.Yeah, I really don't want to use DefaultTreeModel because I would have to wrap my data objects as TreeNodes. Since my data objects are already in a tree structure, implementing TreeModel is much cleaner.
    It looks like I have to implement fireTreeNodesInserted() in my TreeModel, but I guess what I need to understand is how to register the JTree as a listener to my custom TreeModel. JTree doesn't directly implement TreeModelListener. I read somewhere that JTree automatically registers itself with the TreeModel, but that is not what I am observing.
    So..., I am still in need of more info.

  • Where to consume expansion click in JTreeTable?

    Hi!
    I have the following question concerning a JTreeTable (tried it with the classic TreeTableExample2 from http://java.sun.com/products/jfc/tsc/articles/treetable2/index.html ) :
    I want that whenever I click an expand/collapse button of the Tree either the JTable does not change the selection or it does not call my ListSelectionListeners. Where do I have to consume the mouse event on the button so that the JTable does not react? is it possible at all?
    thanks,
    Nils

    To install javascripts in Bridge go to the app preferences and select startup scripts from the list…
    You will then see a button if you click that your folder is revealed… Just pop them in that and restart the app…
    You may be prompted to add new at restart of the app…

  • How to use  myfaces  TreeModel.

    I want to create a Tree view using tomhawk t:tree component.
    This component has a value attribute .
    I want to know
    1-How to use the TreeModel for value binding.
    2-Whether we have to use only TreeModel for value binding or any other wrapper class.
    Thanks Kishan Das.

    Apologies for the late reply, but currently what exists generally for MyFaces integration with Creator is on this blog:
    http://wiki.java.net/bin/view/Javatools/CustomComponentLibraries
    You might also want to post the same question on the nbusers alias on netbeans.org, referencing Visual Web Pack
    Regards,
    -Brad Mayer

  • Changing TreeModel without reference

    HI,
    i have a very basic question. I want to change my tree if the user do some changes in some dialog. So i created an actionEvent in this dialog in order to put the code to change TreeModel.
    The problem is, i dont have a reference of the tree in this dialog and in order to get a reference, i would have to alter many classes.
    Is there a way to change a tree without having a reference on it? This sounds pretty crazy, but i am asking cause i would have to pass the reference from the Main class to the MenuBar, from the MenuBar to another class and then some years later to the dialog.
    i just need some hints which way GUI programmers normally go, i come from the server side, and its not much the same :)
    Marc

    Oh gads... don't do the static thing. The horrors of global variables... will some people never learn.
    Use an Action to construct your menu item that essentially calls a method in some controller class when it's action is triggered.
    Have the controller class that owns the tree (and underlying tree model). The controller will also own the dialog. When the dialog displays, it captures some input. When the dialog is dismissed, the controller will get the return value from the dialog (canceled, etc.) and then get the relevant other data input from the dialog.
    Given the data from the dialog, the controller class will update the tree/treemodel as needed.
    Your menu item (action) should have no knowledge of your tree. Your dialog should have no knowledge of the tree. If you are going to lengths to pass references around, change your approach. Think about where it makes sense for things to reference each other, if it feels odd, look for another way. :-)
    The static suggestions are from lazy programmers who should go back to visual basic and leave the object oriented stuff to us professionals. :-)

  • Question about creating Forms in Java.

    Hello , im new to Java , i find kinda weird how Java creates Forms , its pretty simple in Oracle Forms ,
    why did Java designers make it this difficult ? do people say this is something bad about Java ?
    when i learned about the Layout Managers that Java provides i found out how much code one have to write just to create a simple form ,my question to the experienced java developers : what do you do to create a form , do you hard code it ? , or do you use something like GUI Builder in an IDE like NetBeans for example? and is the code generated by this builder easy to deal with and modify ?
    Thanks ....

    HeavenBoy wrote:
    Hello , im new to Java , i find kinda weird how Java creates Forms , its pretty simple in Oracle Forms ,
    why did Java designers make it this difficult ? do people say this is something bad about Java ?Some Oracle Forms fans certainly do. But the truth is that Oracle Forms application tie down all the components in fixed pixels. The typical Swing form can be resized and can function at different screen resolutions. So, when designing a Java form, we don't tend to work on a fixed grid but define the sizes and positions relative to other components. What's more the interface between the form elements and the data is completely flexible, and flexibility means extra effort.
    >
    when i learned about the Layout Managers that Java provides i found out how much code one have to write just to create a simple form ,my question to the experienced java developers : what do you do to create a form , do you hard code it ? , or do you use something like GUI Builder in an IDE like NetBeans for example? and is the code generated by this builder easy to deal with and modify ?
    Most I've tried have been a bit of a straitjacket, but I've recently been using the latest Netbeans offering and it's pretty good. I think the breakthrough was the introduction of the GroupLayout layout manager. This is a layout manager really designed for WYSIWYG form designers (pretty challenging to use hand coded).
    The way these things work is that the class generated contains some methods which cannot be edited by hand, but you can add any amount of your own code without interfering with the generated code. You hook your own code snippets into the generated code, for example you can select a property of an object, say the model of a JTree, and select "user code", then type in an expression returning the TreeModel you want to use.
    With listeners the designer will generate the method signature etc. but you can edit the body of the listener method.
    However I would always recommend that you hand code a form or two before resorting to on of these editors because it's important you understand the code, even where a designer writes it.

  • JTreeTable component anytime in the future?

    My question is simply whether or not there will be a JTreeTable component in the future?
    I've read Sun's little JTreeTable tutorial (it's kind of dated but it did the job). I created my own TreeTableModel, but I resorted to using Sun's abstract classes and JTreeTable.
    My self-directed project involves getting Foo objects that contain a Vector of child Foo objects and displaying them visually onto a JTreeTable. On top of that, the root node is not a Foo object, instead both it and all Foo objects implement an interface I wrote so that they appear nicely in the JTreeTable.
    Everything works, (it appears that way at least), but I don't feel good about using all that code that I didn't write. That's the reason for me asking the question.

    In short, yes. Don't get me wrong, the code is great and it works. I had to painstakingly adapt TreeTableModel to fit my purposes and I learnt a lot (my main reason for trying to create my program). It's just:
    a) I don't fully understand the code that I haven't written (I'm getting there though)
    b) I'm not really giving credit to the people who wrote it ( I didn't change any of the source files apart from adding tree.setRootVisible(false); to one of the files.
    c) My high school career has forcefully injected the idea "Do not plagiarise" into my head (i'd say figuratively but my head does hurt at times)

  • Question on JUCtrlHierNodeBinding

    my treemodel is ChildPropertyTreeModel, i use this class as ites treenode:
    public class TreeNode implements Serializable
    so the question is : should i change the TreeNode .class to extends the JUCtrlHierNodeBinding so that i can use these code below:
    departmentNew =
    (Number)((JUCtrlHierNodeBinding)richTree.getRowData(rowIndex)).getAttribute("DepartmentId");
    because when i use this code : this exception is thrown : can't cast TreeNode to JUCtrlHierNodeBinding!
    when change to this code is right:
    departmentNew =
    (Number)((TreeNode )richTree.getRowData(rowIndex)).getAttribute("DepartmentId");

    Danny,
    The better question would be "why do you want to cast it to JUCtrlHierNodeBinding?"
    John

  • Does this child node add to the treemodel?

    i've create a treemodel using a list of rootNodes.
    i just wonder if when i create the treemodel and also keep a refference to the rootNodes list.then i add a new node to one of rootnodes as a child.
    so,here is the question:does this child node add to the treemodel?

    i've figure out.it is in memory

  • Refreshing JTree with a customized TreeModel

    Hello,
    I'm newer to Swing, and I'm seeking for help for a JTree problem.
    I hoped to display an XML document with JTree. So I customized a TreeModel and TreeNode to handle the XML data.
    I used DOM to handle XML, and define TreeNode with the following class:
    class DOMtoTreeNode {
    org.w3c.dom.Node domNode;
    public DOMtoTreeNode(org.w3c.dom.Node myNode){
    this.domNode = myNOde; }
    public String toString() {
    //the displaying code
    //and other necessary code to handle children of domNode
    Then I defined an implementation of the TreeModel Interface.
    public class DomTreeModel implements javax.swing.tree.TreeModel
    Document document;
    public DomTreeModel(Document aDomDoc){   
         this.document = aDomDoc;
    // Basic TreeModel operations
    I didn't define any personal TreeModelListener for this TreeModel
    and then I created a JTree object to display the XML tree
    treeModel = new DomTreeModel(someDOMDocument);
    treeInputParameter = new JTree( treeModel );
    and I defined JtreeListener.
    What I hoped to do is to make modification for the XML document in the JTree.
    I added the editing functions in the "valueChanged" function. I added a new DOM node as a child of an existing element node by directly append the child in the DOM node. The code is like the follows:
    DOMToTreeNode treeNodeSelected =(DOMToTreeNode)
    treeInputParameter.getLastSelectedPathComponent();
    org.w3c.dom.Node domNode = treeNodeSelected.getNode();
    //get the dom node from Jtree Node here
    domNode.appendChild(someChildDomNode);
    Up to now, it seems work fine. The TreeModel updates the DOM Document, and the modification being shown in JTree.
    But when I tried to replace an existing node with a new node, something went wrong.
    domNode.replace(newChild, oldChild);
    I debugged the code, and found the underlying DOM Document in the TreeModel had been successfully changed, but the TreeModel didn't update the display in JTree.
    I'm afraid this is quite a naive question, but would someone be kindly help me deal with this? It seems that the reason is that some code is missing to let the TreeModel refresh the frontend JTree display. But I realy don't know how to tackle this.
    Thanks!
    Haoxiang Xia

    Thank you for your reply.
    Are you adding nodes or just expanding the JTree?Adding nodes (I also want to delete nodes)
    I don't know how to do this by just implementing
    TreeModel. This is using DefaultTreeModel.Yeah, I really don't want to use DefaultTreeModel because I would have to wrap my data objects as TreeNodes. Since my data objects are already in a tree structure, implementing TreeModel is much cleaner.
    It looks like I have to implement fireTreeNodesInserted() in my TreeModel, but I guess what I need to understand is how to register the JTree as a listener to my custom TreeModel. JTree doesn't directly implement TreeModelListener. I read somewhere that JTree automatically registers itself with the TreeModel, but that is not what I am observing.
    So..., I am still in need of more info.

Maybe you are looking for

  • Apple ID move to another country

    Hello everybody i moved from Switzerland to Germany and changed the country in my Apple ID in order to have access to the german App Store / iTunes Store. Now I have the problem, that I do not see my purchased item anymore. When I go to iTunes / App

  • ODI-01266: Agent {0} detected Session as stale session and set to error

    Hi I am a beginner in odi I scheduled a package to run . but this error came up :" ODI-01266: Agent {0} detected Session as stale session and set to error status" what is this error and what should i do??? thanx medi

  • URGENT!! CELLWRAPPER single and double quot issues???

    REP-50003: Bad parameter:  CELLWRAPPER='I get this error whenever I try and use single or double quotes as a cellwrapper. However if I do [SPACE][SPACE] as a cell wrapper this works fine?Is this a bug? I'm sure we have version "10.1.2.0.2"?

  • Error when i try to voice chat, whut does this mean

    Date/Time: 2007-05-06 22:44:04.755 -0400 OS Version: 10.4.9 (Build 8P2137) Report Version: 4 iChat Connection Log: AVChat started with ID 2442384591. 0x18025ca0: State change from AVChatNoState to AVChatStateWaiting. bananafish0z7: State change from

  • String Comparsion

    A very basic question regarding strings. I have a String to which I append a "*" at the end of the String ex: S1 - Email Address S2( Appended Label) = Email Address* I have a HashMap - which stores S1. Now I want to compare S1 and S2 (omitting the "*