TreeModel

Hello,
I have custom objects to be put as nodes in a JTree. I am implementing TreeModel Interface but I am not able to achieve insertion/deletion of nodes with it after the JTree has been created.
Is it that if I need to insert or delete a node from JTree then I forcibly should extend DefaultMutableTreeNode and also extend DefaultTreeModel??
Expecting your replies.
S Rao

for addind/deleting you don't need to extend the DefaultMutableTreeNode - it's sufficient for most - applications - what exactly is your problem with adding/deleting? You are creating a new DefaultMutableTreeNode and using <existingnode>.add() to append? and <toBeRemovedNode>.removeFromParent() to remove? Do you call updateUI() for the JTree after each structural change? Otherwise it may happen that the data changes, but that change is not displayed on the screen ...

Similar Messages

  • Runtime dynamic filtering TreeModel

    Hello,
    Changing a tree during runtime seems to be a problem. I've looked at different threads and now I have the following class which filters a delegated DefaultTreeModel (see SimpleFilteredTreeModel and the corresponding TestFilteredTreeModel classes below). Notice, that the commented lines in the isShown-method do filter out alternaitve objects behind the tree at startup of the application correctly.
    I used the following two steps to extend the SimpleFilteredTreeModel to make it refreshing dynamically:
    1. Step: ViewFilter Interface
    First I enabled the SimpleFilteredTreeModel to set filter roules dynamically by introducing an interface (ViewFilter) and three implementions according to the alternatives shown in the isShown method. The filter is set by a method setViewFilter(ViewFilter).
    2. Step: Update the Model
    The method setViewFilter(ViewFilter) basically sets the new filter and tries to update the model so it shows up under the new behaviour.
        public void setViewFilter(ViewFilter filter) {
            this.filter = filter;
            // Notify the model
            final TreeNode root = (TreeNode) getRoot();
            final int childCount = root.getChildCount();
            final int[] indices = new int[childCount];
            final Object[] children = new Object[childCount];
            for (int i = 0; i < childCount; i++) {
                indices[i] = i;
                children[i] = getChild(root, i);
            fireTreeStructureChanged(this, new Object[]{root}, indices, children);
        }However, the view does not move at all. I tried also reload() and nodeChange(root) of the filter model and its delegate. No success.
    If somebody knows how to extend this example to work dynamically, I would appreciate it highly.
    -- Thanks
    -- Daniel Frey
    // File: SimpleFilteredTreeModel.java
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeNode;
    public class SimpleFilteredTreeModel extends DefaultTreeModel {
        private DefaultTreeModel delegate;
        public SimpleFilteredTreeModel(DefaultTreeModel delegate) {
            super((TreeNode) delegate.getRoot());
            this.delegate = delegate;
        public Object getChild(Object parent, int index) {
            int count = 0;
            for (int i = 0; i < delegate.getChildCount(parent); i++) {
                final Object child = delegate.getChild(parent, i);
                if (isShown(child)) {
                    if (count++ == index) {
                        return child;
                else {
                    final Object child2 = getChild(child, index - count);
                    if (child2 != null) {
                        return child2;
                    count += getChildCount(child);
            return null;
        public int getIndexOfChild(Object parent, Object child) {
            return delegate.getIndexOfChild(parent, child);
        public int getChildCount(Object parent) {
            int count = 0;
            for (int i = 0; i < delegate.getChildCount(parent); i++) {
                final Object child = delegate.getChild(parent, i);
                if (isShown(child)) {
                    count++;
                else {
                    count += getChildCount(child);
            return count;
        public boolean isLeaf(Object node) {
            return delegate.isLeaf(node);
        private boolean isShown(Object node) {
            final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
            final Object obj = treeNode.getUserObject();
            //return obj instanceof TestFilteredTreeModel.Datum1 || obj instanceof TestFilteredTreeModel.Datum2;
            //return obj instanceof TestFilteredTreeModel.Datum1;
            return obj instanceof TestFilteredTreeModel.Datum2;
    // File: TestFilteredTreeModel
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    import java.util.ArrayList;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.JTree;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    public class TestFilteredTreeModel {
        private DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[0];
        public static void main(String[] args) {
            new TestFilteredTreeModel();
        public TestFilteredTreeModel() {
            final TreeNode root = createRootNode();
            final TreeModel model = new SimpleFilteredTreeModel(new DefaultTreeModel(root));
            final JTree tree = new JTree(model);
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(tree));
            f.setSize(200, 300);
            f.setVisible(true);
        // Random tree generation
        private Random random = new Random();
        private TreeNode createRootNode() {
            final MutableTreeNode rootNode = createRandomNode();
            updateCache(rootNode);
            for (int i = 0; i < 30; i++) {
                final DefaultMutableTreeNode childNode = createRandomNode();
                pickRandom(nodes).add(childNode);
                updateCache(childNode);
            return rootNode;
        private void updateCache(MutableTreeNode childNode) {
            final List list = new ArrayList(Arrays.asList(nodes));
            list.add(childNode);
            nodes = (DefaultMutableTreeNode[]) list.toArray(new DefaultMutableTreeNode[0]);
        private DefaultMutableTreeNode createRandomNode() {
            final Datum[] data = new Datum[]{new Datum2(), new Datum1()};
            return new DefaultMutableTreeNode(data[random.nextInt(2)]);
        private DefaultMutableTreeNode pickRandom(DefaultMutableTreeNode[] nodes) {
            return nodes[random.nextInt(nodes.length)];
        public static class Datum {
            private static int counter = 0;
            protected int thisCounter = 0;
            public Datum() {
                thisCounter = counter++;
        public static class Datum2 extends Datum {
            public String toString() {
                return "Datum2 " + thisCounter;
        public static class Datum1 extends Datum {
            public String toString() {
                return "Datum1 " + thisCounter;
    // file: ViewFilter.java
    import javax.swing.tree.DefaultMutableTreeNode;
    public interface ViewFilter {
        boolean isShown(DefaultMutableTreeNode node);
    // file: Data1Filter.java
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Data1Filter implements ViewFilter {
        public boolean isShown(DefaultMutableTreeNode node) {
            final Object obj = node.getUserObject();
            return obj instanceof TestFilteredTreeModel.Datum1;
    // file: Data2Filter.java
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Data2Filter implements ViewFilter {
        public boolean isShown(DefaultMutableTreeNode node) {
            final Object obj = node.getUserObject();
            return obj instanceof TestFilteredTreeModel.Datum2;
    // file: Data12Filter.java
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Data12Filter implements ViewFilter {
        public boolean isShown(DefaultMutableTreeNode node) {
            final Object obj = node.getUserObject();
            return obj instanceof TestFilteredTreeModel.Datum1 || obj instanceof TestFilteredTreeModel.Datum2;
    }

    The filtering works (after a fasion). Please clarify your problem.
    I extended SimpleFitleredTreeModel as you described, along with changing isLeaf to use the filter
    if (filter != null)  return filter.isShown( treeNode );I extended TestFiltredTreeModel constructor as follows, add the member
    import javax.swing.*;
    import java.awt.event.*;
    private SimpleFilteredTreeModel model;Altered TestFilteredTreeModel constructor as follows:
           JMenuBar bar = new JMenuBar();
            JMenu menu = new JMenu("Filters");
            JMenuItem item;
            item = new JMenuItem( "Data1Filter" );
            item.addActionListener( new ActionListener() {
                   public void actionPerformed( ActionEvent ev ) {
                        model.setViewFilter( new Data1Filter() );
              menu.add( item );
            item = new JMenuItem( "Data2Filter" );
            item.addActionListener( new ActionListener() {
                   public void actionPerformed( ActionEvent ev ) {
                        model.setViewFilter( new Data2Filter() );
              menu.add( item );
            item = new JMenuItem( "Data12Filter" );
            item.addActionListener( new ActionListener() {
                   public void actionPerformed( ActionEvent ev ) {
                        model.setViewFilter( new Data12Filter() );
              menu.add( item );
            bar.add( menu );
            f.setJMenuBar( bar );

  • 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".

  • ADF: How do I add a node to a selected root in a TreeModel

    I've created a TreeModel with something that follows:
    1.) Loop through a List and build the Roots:
    for (TransactRow transactionRootRow : transactionResults) {
    TransactionNode transactionRootItem = new
    TransactionNode(transactionRootRow.getTransactKey(), transactionRootRow.getParentKey());
    transactionRoot.add(transactionRootItem);
    this.setTransactModel(new ChildPropertyTreeModel(transactionRoot, "children") {
    public boolean isContainer() {
    return ((TransactionNode)getRowData()).getChildCount() > 0;
    This works great.
    What I need to do next is "click" on any of the Roots and add a node to the selected Root.
    I might have:
    |-Root1 (rowKey="r1", rowIndex=0)
    But, when I click on Root1, I should have:
    |-Root1 (rowKey="r1", rowIndex=0)
    | |-Folder1 (rowKey="r1f1", rowIndex=0)
    I am at the point that when I can get the current root in Java code, but how do I go about adding a node to the current root in a TreeModel?
    Thanks,
    --Todd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    This is JSF - ADF specific, but I'm not using JDeveloper.

  • 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

  • How to change TreeModel into DefaultTreeModel?

    //This is my own TreeModel class:
    package xj.guieditor;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import org.w3c.dom.*;
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class MyTreeModel implements TreeModel {
    private Document root;
    public MyTreeModel(Document doc){
    root = doc;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    return ((Node)parent).getChildNodes().item(index);
    public int getChildCount(Object parent) {
    return ((Node)parent).getChildNodes().getLength();
    public boolean isLeaf(Object node) {
    return ((Node)node).getChildNodes().getLength() == 0;
    public void valueForPathChanged(TreePath path, Object newValue) {  }
    public int getIndexOfChild(Object parent, Object child) {
    NodeList nl = ((Node)parent).getChildNodes();
    for(int i=0; i< nl.getLength(); i++)
    if( ((Node)child).equals(nl.item(i)) )
    return i;
    return -1;
    public void addTreeModelListener(TreeModelListener l) {  }
    public void removeTreeModelListener(TreeModelListener l) {  }
    //And in my main file,I parse the xml file like this:
    DOMParser parser = new DOMParser();
    String uri = filename;
    try{
    parser.setIncludeIgnorableWhitespace(true);
    this.setTitle("The current file is: " + uri);
    parser.parse(uri);
    Document doc = parser.getDocument();
    doc.normalize();
    removeWhiteSpaceNodes(doc.getDocumentElement());
    model = new MyTreeModel(doc);
    tree = new JTree(model);
    //And now I want to do some add and remove actions with the xml tree nodes.I want to use the DefaultTreeModel class ,how can I do?Thank you.

    public class MyTreeModel extends DefaultTreeModel {                                                                                                                                                                                                               

  • Are TreePaths only valid in the TreeModel they originate from?

    I've got a JTree that lists our warehouse inventory, grouped by primary and secondary invenotry categories. (IE. "Printers" / "Laser" / "SomeLaserPrinter". ) The tree is populated through a SQL query.
    I've got a checkbox that, when the value changes, decides if the tree should show or hide inventory categories that don't contain any inventory items at the moment.
    What happens when I check/uncheck the box is that the tree is rebuilt from scratch according to it's value.
    Now, if there is something selected in the tree when I click that checkbox, I want the same item to be selected and expanded when the tree is rebuilt. This is where I've been running in to problems.
    The ActionListener for the checkbox is as follows:
    //hideEmptyNodes is the JCheckBox
    hideEmptyNodes.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent e ) {
           try { //inventoryTree is the tree
                TreePath tp = inventoryTree.getSelectionPath();
                 // the InventoryTree.fillWithInventory(boolean hideEmpty) method
                 // clears and populates the tree from a SQL query.
           inventoryTree.fillWithInventory( hideEmptyNodes.isSelected() );
                inventoryTree.expandPath(tp);
                inventoryTree.setSelectionPath(tp);
         } catch ( SQLException ex ) {
           LGRUtils.debugErrln( "Error filling tree." );
        } );This, does NOT work, for some reason. I tried creating the TreePath from the new TreeModel, but still the same:
    hideEmptyNodes.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent e ) {
         try { //inventoryTree is the tree
              Object o = inventoryTree.getLastSelectedPathComponent();
               // the InventoryTree.fillWithInventory(boolean hideEmpty) method
               //clears and populates the tree from a SQL query.
           inventoryTree.fillWithInventory( hideEmptyNodes.isSelected() );
              TreePath tp = new TreePath(
                  ((DefaultTreeModel)inventoryTree.getModel())
                  //SimpleTreeNode extends DefaultMutableTreeNode and only
                  //overrides the boolean equals(Object) method.
                  .getPathToRoot((SimpleTreeNode)o));
              inventoryTree.setSelectionPath(tp);
         } catch ( SQLException ex ) {
           LGRUtils.debugErrln( "Error filling tree." );
        } );Quite frankly, I'm at a loss to how this stuff works. I've searched a bit around the forums, and I've found plenty of other people who have problems with setting the selection paths of trees. None of them have gotten their problems solved in any uniform way, it seems the solution varies from user to user.
    Any pointers to a way of doing this, and making it work, would be greatly appreciated!
    -christig

    First thing I would tell you is that if you will not rebuild a tree from scratch, you will not have this problem!
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • DefaultMutableTreeModel, and casting TreeModel - DefaultMutableTreeModel

    I have a workflow object, from which I create a workflowTreeModel and display this in a JTree - all works OK....
    I now need to create a DefaultMutableTreeModel from the same workflow object and I in need of some pointers. (please)
    All the examples I can find create a number of DefaultMutableTreeNodes (eg, red, blue, green) and add them to a DefaultMutableTreeNode (eg.color)...
    As I already have a workflow object that I am trying to display this approach doesn't fit. Is there anyway to create a DefaultMutableTreeModel in the same way as I am creating the TreeModel?
    Looking at the 'understanding the treeModel' tutorial from Sun I see that I should be able to cast my workflowTreeModel to a DefaultTreeModel using:
    JTree() myTree = new JTree(workflowTreeModel);
    DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();
    However I get a class cast exception trying to do this - I imagine this is as a result of the way the workflowTreeModel is created (code below).
    If anyone can show me the correct way to create a DefaultTreeModel from my workflow object I would be grateful....
    (workflowTreeModel code: )
    public class WorkflowTreeModel extends AbstractWorkflowTreeModel {
         * Commons Logger for this class
        private static final Log logger = LogFactory.getLog(WorkflowTreeModel.class);
        private Workflow rootWorkflow;     
         public WorkflowTreeModel(Workflow root) {
              rootWorkflow = root;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getRoot()
         public Object getRoot() {
              return rootWorkflow.getSequence();
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getChildCount(java.lang.Object)
         public int getChildCount(Object parent) {
              int i = 0;
              if(parent instanceof Workflow) {
                   i = 1;
              else if(parent instanceof Sequence) {
                   Sequence s = (Sequence)parent;
                   i = s.getActivityCount();
              else if(parent instanceof Flow) {
                   Flow f = (Flow)parent;
                   i = f.getActivityCount();
              else if(parent instanceof For) {
                   For f = (For)parent;
                   Sequence s = (Sequence)f.getActivity();
                   i = s.getActivityCount();
              else if (parent instanceof If) {
                   If a = (If)parent;
                   if (a.getElse() != null && a.getElse() instanceof Else)
                        i = i + 1;
                   if (a.getThen() != null && a.getThen() instanceof Then)
                        i = i + 1;
              else if (parent instanceof Else || parent instanceof Then) {
                 i = 1;
              else if (parent instanceof For || parent instanceof Parfor || parent instanceof While) {
                   i = 1;
              else if (parent instanceof Scope) {
                   i = 1;
              else if (parent instanceof Script) {
                   i = 1;
              return i;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#isLeaf(java.lang.Object)
         public boolean isLeaf(Object node) {
              boolean b = true;
              if (node instanceof Sequence) {
                   if (((Sequence)node).getActivityCount() > 0)
                        b = false;
              if (node instanceof Flow) {
                   if (((Flow)node).getActivityCount() > 0)
                       b = false;
              else if (node instanceof If || node instanceof Else || node instanceof Then) {
                   b = false;
              else if (node instanceof For || node instanceof Parfor || node instanceof While) {
                   b = false;
              else if (node instanceof Scope) {
                   b = false;
              else if (node instanceof Workflow) {
                   b = false;
              else if (node instanceof Script) {
                   b = false;
              return b;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#addTreeModelListener(javax.swing.event.TreeModelListener)
         public void addTreeModelListener(TreeModelListener l) {
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#removeTreeModelListener(javax.swing.event.TreeModelListener)
         public void removeTreeModelListener(TreeModelListener l) {
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getChild(java.lang.Object, int)
         public Object getChild(Object parent, int index) {
              Object ob = null;
              if (parent instanceof Workflow){
                   Workflow w = (Workflow)parent;
                   ob = w.getSequence();
              else if(parent instanceof Sequence) {
                   Sequence s = (Sequence)parent;
                   ob = s.getActivity(index);
              else if(parent instanceof Flow) {
                   Flow f = (Flow)parent;
                   ob = f.getActivity(index);
              else if (parent instanceof For) {
                   For f = (For)parent;
                   Sequence s = (Sequence)f.getActivity();
                   ob = s.getActivity(index);
              else if (parent instanceof Parfor) {
                   Parfor p = (Parfor)parent;
                   ob = p.getActivity();
              else if (parent instanceof Scope) {
                   Scope s = (Scope)parent;
                   ob = s.getActivity();
              else if (parent instanceof While) {
                   While w = (While)parent;
                   ob = w.getActivity();
              else if (parent instanceof If) {
                   If i = (If)parent;
                   if (index == 0) {
                        if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                             ob = i.getThen();
                        else if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                             ob = i.getElse();
                   if (index == 1) {
                        if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                             ob = i.getElse();
                        else if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                             ob = i.getThen();
              else if (parent instanceof Else) {
                   Else e = (Else)parent;               
                   ob = e.getActivity();               
              else if (parent instanceof Then) {
                   Then t = (Then)parent;               
                   ob = t.getActivity();               
              else if (parent instanceof Script) {
                   Script s = (Script)parent;
                   ob = s.getBody();
              return ob;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getIndexOfChild(java.lang.Object, java.lang.Object)
         public int getIndexOfChild(Object parent, Object child) {
              logger.debug("getIndexOfChild");
              // TODO Auto-generated method stub
              return -1;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#valueForPathChanged(javax.swing.tree.TreePath, java.lang.Object)
         public void valueForPathChanged(TreePath path, Object newValue) {
              // TODO Auto-generated method stub
    public abstract class AbstractWorkflowTreeModel extends WorkflowTreeModelSupport implements TreeModel {
    }

    JTree() myTree = new JTree(workflowTreeModel);
    DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();the only way you can cast this is that workflowTreeModel must extends DefaultTreeModel
    What you can do is to for WorkFlowTreeMdeol to extends DefaultTreeModel
    or case it to WorkFlowTreeModel
    JTree() myTree = new JTree(workflowTreeModel);
    WorkFlowTreeModel model = (WorkFlowTreeModel) myTree.getModel();

  • 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.

  • JTree making nodes in TreeModel invisible

    I have a TreeModel that represents a database structure. I want to display that structure within a JTree. No problem so far, I just create the JTree using theTreeModel. Everything works great.
    Now, I want some nodes in the tree (tables in the structure) to not be visible to the user, but I cannot remove them from the model. I need the entire db structure intact within the model so all my processing works correctly, but there is no need for the user to be aware of the entire structure.
    Anyway, have any ideas?
    Thanks a bunch.

    Try extending DefaultMutableTreeNode and just had it
    return the count and children of the 'visible' nodes.More info... And maybe add methods getRealChildCount() and getRealChild(int i) so you can manipulate them internally.

  • Insert node into JTree with own TreeModel

    Hi,
    I use JTree in combination with my own TreeModel. When a node is removed I use this to inform all listeners:
    actListener.treeStructureChanged(new TreeModelEvent(this, pathToRoot));The above works fine. Now if I insert a node and its' parent is already expanded nothing happens at all! I tried to call actListener.treeStructureChanged(new TreeModelEvent(this, pathToRoot)); and actListener.insertTreeNodes(new TreeModelEvent(this, pathToRoot)); without success!
    As long as the parent is collapsed and a new node is inserted my getChildCount() method in my TreeModel gets called and the freshly added node will be display correctly but whan the node is already expanded nothing happens.
    I've also checked the listeners of my model: one of them is JTree, so it is informed about the insertions but why won't it update its' view? It's especially funny since everything is fine when deleting a node.
    Many thanks for any hints.
    Regards,
    Ren�

    I am struggling with the same problem, and have yet to find a solution, maybe some more suggestions can be made? Here is the situation... I've got a JTree and a custom TreeModel. Now, if I do not expand a node, I can insert and delete from it at will using treeStructureChanged(new TreeModelEvent(this,path))and when I expand the node it will have the correct children. However, once I have expanded the node, all attempts to add or remove children are futile. Even if I un-expand the node, changes will not register in the JTree. I've tried out both suggestions already provided in this thread, but to no avail. Additionally, if I reset the root node, all my changes will appear correctly, however the trees "expanded" state is lost and this is not desireable.
    Anybody have any advice?

  • How to creating TreeModel of the underlaying drives

    can anybody plz tell me how to creating TreeModel of the underlaying drives. so that we get the entire tree structure of the drives like window explorer.

    This thread will get you started.
    http://forum.java.sun.com/thread.jsp?forum=57&thread=457526

  • 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.

  • JTree (TreeModel) vs (TreeNode)

    hellow,
    I've got some troubles with a tree-view of my data model: I've created my own TreeModel, implemented the necessary methods, ...
    Now, when I try to display the JTree with the TreeNode parameter (I parse the whole data tree) it works perfectly, but when I'm trying the TreeModel parameter, it only shows the root node (I tried "treeStructureChanged (event)" without result).
    Does someone know what I might be forgetting ?
    Can I add a treenodes manually (might give me a clue what I'm doing wrong in my implementation) ?
    thx alot,
    Jerry

    public class X
    static public TreeNode parseDataModel () { ... }
    // parseDataModel() returns the tree root node.
    tree = new JTree(parseDataModel());
    treeView = new JScrollPane(tree);
    frame.getContentPane().add(treeView, BorderLayout.WEST);
    => this works fine
    public class MyTreeModel implements TreeModel { ... }
    MyTreeModel mtm = new MyTreeModel();
    JTree jTree = new JTree (mtm);
    treeView = new JScrollPane(jTree);
    frame.getContentPane().add(treeView, BorderLayout.WEST);
    => only shows the root node (double-clicking it has no effect; it has no 'folder' icon)

  • What is the proper way to reset a CoreTree's TreeModel?

    I have a senerio in which I need to clear out a CoreTree on an event - remove all roots and nodes and re-populate the CoreTree with new data.
    I've tried to nullify the CoreTree's TreeModel.
    I've tried using the PathSet:
    PathSet pathSetTransact = this.getTransactTree().getTreeState();
    if(pathSetTransact != null){
    Set ks = pathSetTransact.getKeySet();
    ks.clear();
    Neither of these work.
    What is the proper way to reset a CoreTree's TreeModel?
    Thanks,
    --Todd
    Also, in your code snippet, root isn't even used?
    Message was edited by:
    jtp51

    OK.
    This just isn't working.
    Setting my CoreTree's TreeModel with an empty GenericTreeNode does not clear out the previously populated tree.
    What other path could I take to accomplish my goal?
    Thanks,
    --Todd                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Dynamically adding nodes without a TreeModel

    Hi,
    I am adding nodes dynamically after the tree is visible. It's adding
    the first child node I create and it is showing it. When I add a second
    node, it doesn't show the that. And when I debug the code I found that
    the node was added to the tree but it is not visible. I tried by
    expanding and collapsing the tree manually, but it didn't work.
    I am not using any TreeModel as such. So, how do I make the change
    visible??? I am even calling the repaint() method of JTree, what could
    be the problem and is it better if I create my own TreeModel class and
    use it???
    Thank you,
    Srikanth...

    you can post the code for start.
    try to get the model and fire
    fireTreeStructureChanged(that will collapse all)
    or try to fire fireTreeNodesInserted
    for my point of view
    implamenting the TreeModel is always better and simple

Maybe you are looking for

  • New Macbook - Airport connection problem

    Hi All, wondering if someone can help. I have just bought a new MacBook (yesterday) and have been trying to connect to the wireless network that I currently use with my Powerbook. I can connect the new MacBook to the Airport Express to play AirTunes

  • Brush Disappears with Increased Brush Size

    Having issues with my news CS4. When I increase my brush size, no matter if it's an eraser, stamp tool or anything else, the brush cursor or "circle" starts to disappear once the brush is more than 175 pixels in diameter. I've checked preferences and

  • ABAP dump analysis

    HI all Pl let me know ABAP Dump analysis .which type of abap dump problems arrived every time. pl explain explain more than two or three  examples recently u face abap dumps and solutions hoe u resolved that problems [removed by moderator] I really a

  • OIM 11g Login page not loading properly

    Hi, I have configured a new OIM 11g environment in a Linux environment. All my applications were running fine. I was able to work on OIM administrator and Design Console (Client). Suddenly the OIM 11g administrator login screen is not loading properl

  • CreateInsert in Train Bounded Task Flow

    Jdev 11.1.1.5.0 I have bounded task flow with train behavior. There are two pages, the welcome page and the create page. The train is connected from the welcome page to create page. So, the connection is something like this: welcome page --------> cr