JTree difficulties

Hi,
I wish to generate a popup for multiple nodes selected on a JTree. I need to query the nodes user objects to decide on the contents of the popup. How can I get the user objects of the selected nodes when the selection methods simply return TreePaths??
Also, I have installed a custom editor for my nodes. It is a Box container that contains a JLabel and a JTextField. Here is the code:
public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
ce.setText(getUserObject().toString());
if (isSelected) {
ce.setOpaque(true);
treeLabel.setOpaque(true);
} else {
ce.setOpaque(false);
treeLabel.setOpaque(false);
treeLabel.setText(makePresetName(preset, ""));
treeLabel.setIcon(getIcon());
treeLabel.setToolTipText(getToolTipText());
Box box = Box.createHorizontalBox();
box.add(treeLabel);
box.add(ce);
return box;
Problem is the JLabel(with its icon) never gets shown, just the JTextField component.
What could be happening here??
-Paul.

((DefaultMutableTreeNode)selectedTreePath.getLastPathComponent()).getUserObject()Sven

Similar Messages

  • JTree editing difficulties

    I am having trouble with the editor on the JTree. I am trying to make it possible for the user to right click on an element of the Tree, have a pop-up menu come up with an option "Rename", have the user edit the name, and then have the name changed. It is almost working as described. The difficulty is that when the user has finished editing, the name is changed properly, but the displayed name is clipped in the wrong place.
    More particularly, what happens is as follows:
    1. The user right-clicks on an existing leaf
    2. The pop-up menu comes up with the rename option
    3. The icon disappears and the user sees a box to type the changes into, as per spec
    4. The user makes his/her change
    5. The name is changed properly, but the display acts as though it were clipped at the point where the right side of the text would have been, had the icon not been there. It is as though the right side of the display does not move, but the left side does, for some reason.
    Any ideas of what is going wrong/workarounds?

    I'm afraid that doesn't work. I both revalidate and then repaint, but it still acts the same.
    Perhaps I should make one point clear: The user can always edit the tree by double-clicking on the leaf. That works fine. It's just the editing induced directly in my personal code that has trouble.
    The code is essentially as follows:
    To add the rename item to the pop-up menu:
    renameItem.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                    TreePath toEditPath = theEnvelope.getTreePathTo( selectedObject );
                    jTree1.startEditingAtPath( toEditPath );
            } );The tree has the following listener on it:
    CellEditorListener newTreeCellListener = new CellEditorListener() {
                public void editingCanceled( ChangeEvent e) {
                public void editingStopped( ChangeEvent e ) {
                    Object newVal = ((DefaultCellEditor)e.getSource()).getCellEditorValue();
                    Object oldVal = ((EquationTreeCellEditor)e.getSource()).getEditedEquationManager();
                    //Make sure it changes the name only if the name has actually been changed, not
                    //just edited
                    if ( oldVal instanceof EquationManager ) oldVal = ((EquationManager)oldVal).getName();
                    if ( !oldVal.equals( newVal.toString() ) ) {
                        renameEquationManager( oldVal, newVal );
            } ;However, this listener is invoked both when the editing was initiated with the popup menu and when the user double-clicked. The regular double-clicking method works while the right-clicking one does not.

  • Display JTree in browser using JSP

    i have a program that converts xml file in to tree structure(using Swing). When i run this using eclipse then it is working. Swing is an extension of applet , right. I want to embed this in an HTML page(JSP). so that i can display the tree structure. Its gives class not foung error.
    It is not posiible to embed it. I think if it extends an Applet then it will display. But i don't know how to convert that. It gives error if i convert.
    pls help
    CODE:
    package TreeGen;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import java.io.IOException;
    import org.w3c.dom.Document;
    // Basic GUI components
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    // GUI components for right-hand side
    import javax.swing.JSplitPane;
    import javax.swing.JEditorPane;
    // GUI support classes
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    // For creating borders
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    // For creating a TreeModel
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    public class TreeGen extends JPanel
         static Document document;
         boolean compress = false;
         static final int windowHeight = 660;
         static final int leftWidth = 300;
         static final int rightWidth = 640;
         static final int windowWidth = leftWidth + rightWidth;
         public TreeGen()
         EmptyBorder eb = new EmptyBorder(5,5,5,5);
         BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
         CompoundBorder cb = new CompoundBorder(eb,bb);
         this.setBorder(new CompoundBorder(cb,eb));
         JTree tree = new JTree(new DomToTreeModelAdapter());
         JScrollPane treeView = new JScrollPane(tree);
         treeView.setPreferredSize(
              new Dimension( leftWidth, windowHeight ));
         final
         JEditorPane htmlPane = new JEditorPane("text/html","");
         htmlPane.setEditable(true);
         JScrollPane htmlView = new JScrollPane(htmlPane);
         htmlView.setPreferredSize(
              new Dimension( rightWidth, windowHeight ));
         tree.addTreeSelectionListener(
              new TreeSelectionListener()
              public void valueChanged(TreeSelectionEvent e)
                   TreePath p = e.getNewLeadSelectionPath();
                   if (p != null)
                   AdapterNode adpNode =
                        (AdapterNode) p.getLastPathComponent();
                   htmlPane.setText(adpNode.content());
         JSplitPane splitPane =
              new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                                  treeView,
                                  htmlView );
         splitPane.setContinuousLayout( false );
         splitPane.setDividerLocation( leftWidth );
         splitPane.setDividerSize(1);
         splitPane.setPreferredSize(
                   new Dimension( windowWidth + 10, windowHeight+10 ));
         this.setLayout(new BorderLayout());
         this.add("Center", splitPane );
         //return menuBar;
         } // constructor
         public static void main(String argv[])
              DocumentBuilderFactory factory =
                   DocumentBuilderFactory.newInstance();
              try {
              DocumentBuilder builder = factory.newDocumentBuilder();
              document = builder.parse("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/parser1/sample.xml");
                   makeFrame();
              } catch (SAXException sxe){
                   System.out.println("ERROR");
              Exception x = sxe;
              if (sxe.getException() != null)
                   x = sxe.getException();
              x.printStackTrace();
              } catch (ParserConfigurationException pce) {
                   pce.printStackTrace();
              } catch (IOException ioe) {
              ioe.printStackTrace();
         } // main
         public static void makeFrame()
              JFrame frame = new JFrame("DOM Echo");
              frame.addWindowListener(
              new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {System.exit(0);}
              final TreeGen echoPanel =
              new TreeGen();
              frame.getContentPane().add("Center", echoPanel );
              frame.pack();
              Dimension screenSize =
              Toolkit.getDefaultToolkit().getScreenSize();
              int w = windowWidth + 10;
              int h = windowHeight + 10;
              frame.setSize(w, h);
              frame.setVisible(true);
         } // makeFrame
         static final String[] typeName = {
              "none",
              "Element",
              "Attr",
              "Text",
              "CDATA",
              "EntityRef",
              "Entity",
              "ProcInstr",
              "Comment",
              "Document",
              "DocType",
              "DocFragment",
              "Notation",
         static final int ELEMENT_TYPE = 1;
         static final int ATTR_TYPE = 2;
         static final int TEXT_TYPE = 3;
         static final int CDATA_TYPE = 4;
         static final int ENTITYREF_TYPE = 5;
         static final int ENTITY_TYPE = 6;
         static final int PROCINSTR_TYPE = 7;
         static final int COMMENT_TYPE = 8;
         static final int DOCUMENT_TYPE = 9;
         static final int DOCTYPE_TYPE = 10;
         static final int DOCFRAG_TYPE = 11;
         static final int NOTATION_TYPE = 12;
    static String[] treeElementNames = {
              "slideshow",
              "slide",
              "title", // For slideshow #1
              "slide-title", // For slideshow #10
              "item",
         boolean treeElement(String elementName) {
         for (int i=0; i<treeElementNames.length; i++) {
              //System.out.println(treeElementNames);
              if ( elementName.equals(treeElementNames[i]) )
              return true;
         return false;
         public class AdapterNode
         org.w3c.dom.Node domNode;
         public AdapterNode(org.w3c.dom.Node node)
              domNode = node;
         public String toString()
              String s = typeName[domNode.getNodeType()];
              String nodeName = domNode.getNodeName();
              if (! nodeName.startsWith("#"))
              s += ": " + nodeName;
              if (compress)
              String t = content().trim();
              int x = t.indexOf("\n");
              if (x >= 0) t = t.substring(0, x);
              s += " " + t;
              return s;
              if (domNode.getNodeValue() != null)
              if (s.startsWith("ProcInstr"))
                   s += ", ";
              else
                   s += ": ";
              // Trim the value to get rid of NL's at the front
              String t = domNode.getNodeValue().trim();
              int x = t.indexOf("\n");
              if (x >= 0) t = t.substring(0, x);
              s += t;
              return s;
         public String content()
              String s = "";
              org.w3c.dom.NodeList nodeList = domNode.getChildNodes();
              for (int i=0; i<nodeList.getLength(); i++)
              org.w3c.dom.Node node = nodeList.item(i);
              int type = node.getNodeType();
              //System.out.println(type);
              AdapterNode adpNode = new AdapterNode(node); //inefficient, but works
              if (type == ELEMENT_TYPE)
                   if ( treeElement(node.getNodeName()) ) continue;
                   s += "<" + node.getNodeName() + ">";
                   s += adpNode.content();
                   s += "</" + node.getNodeName() + ">";
              else if (type == TEXT_TYPE)
                   s += node.getNodeValue();
              else if (type == ENTITYREF_TYPE)
                   s += adpNode.content();
              else if (type == CDATA_TYPE)
                   StringBuffer sb = new StringBuffer( node.getNodeValue() );
                   for (int j=0; j<sb.length(); j++)
                   if (sb.charAt(j) == '<')
                        sb.setCharAt(j, '&');
                        sb.insert(j+1, "lt;");
                        j += 3;
                   else if (sb.charAt(j) == '&')
                        sb.setCharAt(j, '&');
                        sb.insert(j+1, "amp;");
                        j += 4;
                   s += "<pre>" + sb + "\n</pre>";
              return s;
         public int index(AdapterNode child)
              int count = childCount();
              for (int i=0; i<count; i++)
              AdapterNode n = this.child(i);
              if (child.domNode == n.domNode) return i;
              return -1; // Should never get here.
         public AdapterNode child(int searchIndex)
              org.w3c.dom.Node node =
                   domNode.getChildNodes().item(searchIndex);
              if (compress)
              int elementNodeIndex = 0;
              for (int i=0; i<domNode.getChildNodes().getLength(); i++)
                   node = domNode.getChildNodes().item(i);
                   if (node.getNodeType() == ELEMENT_TYPE
                   && treeElement( node.getNodeName() )
                   && elementNodeIndex++ == searchIndex)
                   break;
              return new AdapterNode(node);
         public int childCount()
              if (!compress)
              return domNode.getChildNodes().getLength();
              int count = 0;
              for (int i=0; i<domNode.getChildNodes().getLength(); i++)
              org.w3c.dom.Node node = domNode.getChildNodes().item(i);
              if (node.getNodeType() == ELEMENT_TYPE
              && treeElement( node.getNodeName() ))
                   ++count;
              return count;
         public class DomToTreeModelAdapter
         implements javax.swing.tree.TreeModel
         public Object getRoot()
              return new AdapterNode(document);
         public boolean isLeaf(Object aNode)
              AdapterNode node = (AdapterNode) aNode;
              if (node.childCount() > 0) return false;
              return true;
         public int getChildCount(Object parent)
              AdapterNode node = (AdapterNode) parent;
              return node.childCount();
         public Object getChild(Object parent, int index)
              AdapterNode node = (AdapterNode) parent;
              return node.child(index);
         public int getIndexOfChild(Object parent, Object child)
              AdapterNode node = (AdapterNode) parent;
              return node.index((AdapterNode) child);
         public void valueForPathChanged(TreePath path, Object newValue)
         private Vector listenerList = new Vector();
         public void addTreeModelListener(TreeModelListener listener)
              if ( listener != null
              && ! listenerList.contains( listener ) )
              listenerList.addElement( listener );
         public void removeTreeModelListener(TreeModelListener listener)
              if ( listener != null )
              listenerList.removeElement( listener );
         public void fireTreeNodesChanged( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesChanged( e );
         public void fireTreeNodesInserted( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesInserted( e );
         public void fireTreeNodesRemoved( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesRemoved( e );
         public void fireTreeStructureChanged( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeStructureChanged( e );

    I actually had to do this a few months ago. There are ways to perform this kind display using various distributed object (i.e., using MS Word OLE objects to "interpret" the byte for you, etc.). But this soon got extremely difficult to manage (and I actually had to use Perl/CGI for the majority of it).
    The solution I went with was to implement a "cache" directory on the web server. Basically, the JSP/Servlet can simply check the cache and if file not there, create it from the database. Then send a redirect back to the browser to this newly-created file. The browser will then appropriately open the document. I tested this with both Netscape and IE browsers and common MIME types such as text files, MS Office docs, zip files, PDFs, RTFs.
    Not ideal, but unfortunately the best I came up with.

  • What's a good way to show attributes in a JTree made from DOM?

    I'm doing a pretty simple project that's basically just taking an XML document, making a DOM out of it, and then I want to represent the document in a JTree. The code I have now works swimmingly, except it doesn't do anything about attributes. Ideally (for the purposes of the tree), I'd like the attributes to show up as children of the node of which they are an attribute, and then each attribute node would itself have a child representing the value.
    basically I want to go from this:
    <xmlNode attribute=value>
       <child>
       </child>
    </xmlNode>To a JTree like this ('v' being the expansion arrow on the tree):
    v xmlNode
       v attribute
          v value
       v childI realize they're not of equivalent meaning, but for my purposes representing the true structure of the XML is not as important as meaningfully representing the information it contains.
    My question is basically, is there a more straightforward way to accomplish this than to manually add children nodes for all of the attributes? How would you approach this problem? I'm not looking for code or for someone to give me the "answer," I just wanted to get a second opinion.

    camickr and DrClap, thanks for your ideas! Both of those solutions seem pretty reasonable for what I'm doing, I'll experiment with them (I do indeed already have a custom Tree model, so adding this in wouldn't actually be too difficult... I don't know why that didn't occur to me!).
    Thanks for the replies!

  • Disableing nodes in JTree

    Hi All,
    is it possible to disable the nodes in a JTree. i.e. Grey them out, so user is not able to select.
    thanks

    if you use DefaultMutableTreeNode as your node's class, than it's not possible (does not contain any parameter to provide this functionality),
    but you can make your own derivation of this class, when you do it yourself
    (an interesting design question: what would you expect the disabled note to do? if you have some user-assigned action, you could probably disable it quite easily, but if you want to prevent the disabled note to be scrolled-up/down, I'm afraid it would be a bit more difficult)

  • How can one resize a cell editor when in use in a JTree?

    It is possible to resize, for example, a JTextArea cell editor while it is being used in a JTable by having a document listener check the preferred height and then changing the rowHeight of the table to fit that. This gives the nice effect of the table expanding and contracting in size as required while it is being edited.
    I would also like to this this for a Jtree. But one cannot reset the height of an individual JTree row, and although it can be set up to get the correct height when the editor or renderer is installed (via setRowHeight(0)), there does not seem to be a way to dynamically adjust this height while editing.
    This would be very nice to be able to do. (I would say it should be required of a good tree component that it allow this).
    Is there some way I am missing? It seems like there is no difficult constraint on the design of Jtree which should make this difficult in principle.

    You cannot download apps from another country's store unless you have an account in that country which means having a credit card that is tied to a physical address in that country.
    AFAIK, you cannot add more dictionaries to the collection that. Apple has provided. There is no way to add any plug ins, or enhancements to any of the built to in apps or iOS functions.

  • PutClientProperty("JTree.lineStyle", "Angled") in JDK 1.4.2

    In 1.4.2 the look of the tree has been updated to remove the ---- line handles on the tree by default. I would like to continue displaying those as they appeared in earlier versions without using the older classic windows look and feel for the rest of the application (so I don't want to use the command line toggle that alters this).
    Has anyone gotten the above client property to work properly on the tree in 1.4.2? I've been having difficulties with this. I generally do something like the following:
    tree.putClientProperty("JTree.lineStyle", "Angled");
    tree.repaint();
    OR
    tree.updateUI();
    Would it also be possible to override this for all instances of JTree's in the application by setting something in the UIManager?

    There seems to be a great deal of confusion here.
    The property "JTree.lineStyle" is (unfortunately) only used by
    MetalTreeUI, and won't have any effect in the Windows L&F. It is a
    client property, which (unfortunately) is a different mechanism from
    the UIManager defaults.
    The bug is in WindowsTreeUI and will be fixed in 1.5. There is no
    easy workaround, except to replace the UI class with a fixed one. Here
    is an attempt which seems to work. I don't give any guarantees, but
    please let me know how it works for you.
    import com.sun.java.swing.plaf.windows.WindowsTreeUI;
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.*;
    import javax.swing.tree.*;
    * A subclass of JTree that fixes bug 4887931: Tree lines
    * missing on Windows XP
    public class JTree14 extends JTree {
        public JTree14() {
        public JTree14(Object[] value) {
         super(value);
        public JTree14(Vector value) {
         super(value);
        public JTree14(Hashtable value) {
         super(value);
        public JTree14(TreeNode root) {
         super(root);
        public JTree14(TreeNode root, boolean asksAllowsChildren) {
         super(root, asksAllowsChildren);
        public JTree14(TreeModel newModel) {
         super(newModel);
        public void setUI(TreeUI ui) {
         if (ui instanceof WindowsTreeUI &&
             System.getProperty("java.version").equals("1.4.2")) {
             ui = new FixedWindowsTreeUI();
         super.setUI(ui);
        private static class FixedWindowsTreeUI extends BasicTreeUI {
         protected void ensureRowsAreVisible(int beginRow, int endRow) {
             if(tree != null && beginRow >= 0 && endRow < getRowCount(tree)) {
              Rectangle visRect = tree.getVisibleRect();
              if(beginRow == endRow) {
                  Rectangle     scrollBounds = getPathBounds(tree, getPathForRow
                                              (tree, beginRow));
                  if(scrollBounds != null) {
                   scrollBounds.x = visRect.x;
                   scrollBounds.width = visRect.width;
                   tree.scrollRectToVisible(scrollBounds);
              else {
                  Rectangle   beginRect = getPathBounds(tree, getPathForRow
                                         (tree, beginRow));
                  Rectangle   testRect = beginRect;
                  int         beginY = beginRect.y;
                  int         maxY = beginY + visRect.height;
                  for(int counter = beginRow + 1; counter <= endRow; counter++) {
                   testRect = getPathBounds(tree,
                                   getPathForRow(tree, counter));
                   if((testRect.y + testRect.height) > maxY)
                       counter = endRow;
                  tree.scrollRectToVisible(new Rectangle(visRect.x, beginY, 1,
                                        testRect.y + testRect.height-
                                        beginY));
         protected TreeCellRenderer createDefaultCellRenderer() {
             return new WindowsTreeUI().new WindowsTreeCellRenderer();
    }Cheers,
    Leif Samuelsson
    Java Swing Team
    Sun Microsystems, Inc.

  • Portable file system jtree based on FileSystemView

    Does anybody know of an open source widget that meets this description?
    I wrote just a basic explorer style widget that works on linux and win32, but it doesn't use the shell that most win32 users expect (and that I now hate with a passion)- i.e. Desktop/My Documents/etc.
    This bogus win32 file shell is available through filesystemview, but sticking this into a jtree and having it work on every OS and also having features like being able to set a selected node by passing in a file object... well that ends up being a pretty advanced topic. Having to spend a week writing a component that is readily available in any win32 programming language really bites.
    Anbody know of anything that may help?

    Thats what I have written already, w/o a severe degree of difficulty.
    Unfortunately, this type of implementation differs greatly from what users in the year 2003 are used to seeing in their win32 desktop apps. Heck, novice users who are new to PCs may never find "Desktop" in a JTree if they are left to fend for themselves and figure out where it is buried! i.e. C:\Documents and Settings\byoung\Desktop. You may say, "Not my problem"... however when you are selling your app and people choose not to buy it because it isn't "novice friendly", well then it becomes your problem very quickly.
    Unfortunately, the way Micro$oft has messed up the file system by using this bogus shell crap, the file system is no longer even a true hierarchy... it is partly busted. It is then very difficult to use the same widget code (such as a tree) based on a FileSystemView that is truely cross-platform. Not very nice... not very nice at all.

  • Using JTree with checkbox

    Hi All,
    I have a link for implementation of JTree with Checkbox
    http://www.jroller.com/santhosh/date/20050610 He has implemented exactly what i want but i am unable to understand the use of all the classes. Really difficult to understand
    So what i did was create a few objects with Checkbox class from AWT package and then added then to JTree using the DefaultMutableTreeStruture i got the tree working but not able to get the Checkboxex
    Can any one explain me how i can implement this senario
    I am trying different search creterias but unable to find a right detailed explanation to my query
    Rgds
    Aditya

    where did you find DefaultMutableTreeStructure?

  • How remove (or change) children inside a JTree

    hi,
    I did a program where there are informations with a structure of dependence that should be showed inside JTree components.
    I realized this purpose in my program .
    But I am findind very difficult (after having put the information inside the JTre in the start) to show them again inside the JTrees when they are changed.
    I don't know how to remove or change the informations after they are put on the children of the JTree using the methods that I found in the documentation to reach this purpose...
    I need some help ...
    To explain well my problem, and facilitate the helpers, I post some code that show my problem..
    The program show a GUI with some JTrees.
    The informations are contained in two strings, and in the GUI are also two buttons that can load the informations inside the JTree when they are clicked.
    Thank you in advance
    regards
    tonyMrsangelo
    public class JTree_TryToUseIt_ChangingNodes extends javax.swing.JFrame {
        private PanelFulViewConteiner jPanelFulViewConteiner;
        Dimension dimPrefArcPanels = new Dimension(910, 150);
        Dimension dimMinArcPanels = new Dimension(700, 100);
        Dimension dimPrefSemiArcPanels = new Dimension(850, 140);
        Dimension dimMinSemiArcPanels = new Dimension(550, 90);
        Dimension dimPrefBodyXpicPanels = new Dimension(900, 150);
        Dimension dimMinBodyXpicPanels = new Dimension(700, 150);
        Dimension treePrefDim = new Dimension(90, 110); //
        Dimension treeMinDim = new Dimension(60, 110);
        PanelToShowTrees panel_trees;
        public JTree_TryToUseIt_ChangingNodes() {
            getContentPane().setLayout(new GridBagLayout());
            GridBagConstraints gBC = new GridBagConstraints();
            jPanelFulViewConteiner = new PanelFulViewConteiner();
            gBC.gridx = 0;
            gBC.gridy = 0;
            gBC.gridwidth = 10;
            add(jPanelFulViewConteiner, new GridBagConstraints());
            gBC.gridx = 0;
            gBC.gridy = 1;
            gBC.gridwidth = 10;
            pack();
            panel_trees = this.jPanelFulViewConteiner.jPanelFulContainerTop.panelToShowTrees;
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocation(50, 50);
            setVisible(true);
        private void fillTrees(String[] strings) {
            collapseTrees();
            removeNodes();
            for (int index = 0; index < strings.length; index++) {
                DefaultMutableTreeNode dmt = new DefaultMutableTreeNode(strings[index]);
                String knotStr = strings[index].substring(0, 1);
                int knot = -1;
                try {
                    knot = Integer.parseInt(knotStr);
                } catch (NumberFormatException e) {
                panel_trees.root_Node[knot].add(dmt);
                panel_trees.validate();
                panel_trees.repaint();
            collapseTrees();
        void collapseTrees() {
            for (int i = 0; i < 8; i++) {
                panel_trees.jTree.collapseRow(0);
    panel_trees.jTree[i].expandRow(0);
    panel_trees.validate();
    panel_trees.repaint();
    void removeNodes() {
    for (int i = 0; i < 8; i++) {
    panel_trees.jTree[i].removeAll();
    panel_trees.validate();
    panel_trees.repaint();
    public static void main(String args[]) {
    JTree_TryToUseIt_ChangingNodes xx = new JTree_TryToUseIt_ChangingNodes();
    class PanelFulViewConteiner extends JPanel {
    PanelFulContainerTop jPanelFulContainerTop;
    PanelFulContainerBottom jPanelFulContainerBottom;
    public PanelFulViewConteiner() {
    GridBagLayout gbl = new GridBagLayout();
    this.setLayout(gbl);
    GridBagConstraints gBC = new GridBagConstraints();
    jPanelFulContainerTop = new PanelFulContainerTop();
    gBC.gridx = 0;
    gBC.gridy = 0;
    add(jPanelFulContainerTop, gBC);
    jPanelFulContainerBottom = new PanelFulContainerBottom();
    gBC.gridx = 0;
    gBC.gridy = 2;
    add(jPanelFulContainerBottom, gBC);
    class PanelFulContainerTop extends JPanel {
    PanelToShowTrees panelToShowTrees;
    public PanelFulContainerTop() { // costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    setLayout(new FlowLayout());
    panelToShowTrees = new PanelToShowTrees();
    add(panelToShowTrees);
    }// costruttore
    class PanelFulContainerBottom extends JPanel {
    JButton but1 = new JButton("load string1");
    JButton but2 = new JButton("load string2");
    String[] str1 = {"0-AAA", "0-BBBBBB", "2-CCCCC", "2-DDDDDD", "2-EEEEEEE", "5-FFFFFF", "5-GGGGGG", "5-HHHHHH", "7-IIIIII", "7-KKKKKKK", "7-LLLLLL", "7-MMMMMM"};
    String[] str2 = {"0-aaaaa", "0-bbbbb", "0-cccc", "2-ddddd", "2-eeee", "3-ffffff", "3-gggggg", "3-hhhhh", "4-iiiiii", "4-kkkkk", "7-lllllll", "7-mmmmm", "7-nnnnn"};
    public PanelFulContainerBottom() {// costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    add(but1);
    but1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str1);
    add(but2);
    but2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str2);
    class PanelToShowTrees extends JPanel {
    JScrollPane jScrollPane[];
    JTree jTree[];
    DefaultMutableTreeNode[] root_Node;
    public PanelToShowTrees() {
    this.setMinimumSize(dimMinSemiArcPanels);
    this.setPreferredSize(dimPrefSemiArcPanels);
    setLayout(new FlowLayout());
    jScrollPane = new JScrollPane[8];
    jTree = new JTree[8];
    root_Node = new DefaultMutableTreeNode[8];
    for (int i = 0; i < 8; i++) {
    root_Node[i] = new DefaultMutableTreeNode(" " + (8 - i));
    jTree[i] = new JTree(root_Node[i]);
    jScrollPane[i] = new JScrollPane();
    jScrollPane[i].setViewportView(jTree[i]);
    add(jScrollPane[i]);
    jScrollPane[i].setPreferredSize(treePrefDim);
    jScrollPane[i].setMinimumSize(treeMinDim);
    jTree[i].addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    showContentOfTheTree(e);
    private void showContentOfTheTree(TreeSelectionEvent e) {
    String stringaGotFromEvent = e.getPath().toString();
    JOptionPane.showMessageDialog(rootPane, "found =---> " + stringaGotFromEvent);

    hi Andre,
    thank you for answering me.
    I have not much practice with JTrees so I find some difficulty to use it...
    After I got your advice, I made changed a little the design of my program..
    This it is a program for management of a dentist office, and I would show in 8 JTrees (every jTree root represents the teeth in a dental arch) the treatments that each tooth got.
    How I said, the 8 JTree roots are representing the teeth, and in this architecture the problem is:
    - to add a node to a tree root to indicate a treatment for that tooth;
    - to delete all the children from a jTree root before beginning to add new child, before writing again treatments, when the informations are changed.
    Following your help, I made this two functions to reach this purpose:
    private void assingTreatmentToTooth(int toothNmbr, String strTreatment) {
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // new treatment to add
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel(); // get model for the root Tree
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
            model.insertNodeInto(newChild, parentNode, 0); // always assign 0 as first node
        } // assingTreatmentToTooth()
    private void removeTreatmentFromAtooth(int toothNmbr, int childNmbr) {
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel();  // get model for the root Tree
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
            model.removeNodeFromParent(child);
        } // removeTreatmentToTooth()when the second function is executed, I get this error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.tree.DefaultTreeModel cannot be cast to javax.swing.tree.TreeNode
    at the line : DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    could you tell me what is wrong ?
    regards
    TonyMrsangelo

  • Does setSelectionPath() method of JTree calls the treeValueChanged() method

    Hello,
    Just wanted to know whether setSelectionPath() method of JTree calls the treeValueChanged() method after selecting the path?
    Thanks.

    Hi SaucyMexican,
    Thank you for using Apple Support Communities. 
    It looks like PayPal is still an accepted form of payment for the Apple Store:
    Payment methods you can use in the iTunes Store, Mac App Store, App Store, and iBooks Store - Apple Support
    If you are still having difficulties you can take a look at this article for assistance.
    Change or remove your payment information from your iTunes Store account (Apple ID) - Apple Support
    Regards,
    Jeff D. 

  • DnD from JTree to JTable

    Hi guys,
    It seems JTree DnD support is a quit difficult feature to implement of all swing components.
    I'm writing an application in which I have a JTree structure representing the file system of user machine and another JTable component at the right.
    I want to be able to drag files nodes from left JTree to right JTable.
    I would appreciate a lot if someone share with me some source code examples for this functionality.
    can someone post some basic java code to get me started or point me to some web resource discussing this feature?
    thanks much.

    http://forum.java.sun.com/thread.jspa?threadID=296255Thank you. I already looked at this thread but it's not what i'm looking for: it shows dnd from a JTree to another JTree..however i need to implement dnd from JTree to JTable.
    Is there some basic example on how to do that ?
    thanks.

  • Drag n Drop in JTree - missing the visual effect

    Hi,
    I already implemented the D&D on Jtree (from a JList)
    I've implemented DropTargetListener and it works
    I've the visual effect of the Dragged object on the mouse
    I have an extended DefaultTreeCellRenderer witch I use for other things.
    My problem is how do I get the visual effect of the active tree nodes when I drag it over them ?
    thanks,
    Allen

    Drag and drop is not something you can just turn on and off im afraid. You have 2 choices:
    1. if the dragging and dropping only occurs over a single component such as your tree, you could probably make a simplified on with mouse [motion?] listeners. On a mouse drag it could check which node was under the drag point and keep that in a variable. On a mouse release it could look to see if theres a node there and if so make it a child of that node.
    2. Implement full drag and drop, subclassing the JTree and having both a DragSource and DropTarget assigned to it. Theres a load of interfaces to implement but its not too difficult. Youll also need to make a DataFlavor class to contain the node values. Its the more involved solution but would probably be better in the long run.
    DS

  • Updating JTree from Vector

    Hello,
    i'm using a JTree and buildings its Tree from a Vector.
    Vector root = new Vector();
    Vector child1 = new Vector();
    Vector child2 = new Vector();
    child1.add(new String("Test1"));
    child1.add(new String("Test12"));
    child2.add(new String("Child2"));
    root.add(child1);
    root.add(child2);
    JTree myTree = new JTree(root);
    Now i have the problem that Item Test1 from child1 is changig to child2. Doing this at the vector level is not difficult, but how can i get the JTree taking this changes?

    JTree will lie dormant until it receives a nodesWereChanged, nodesWereDeleted or whatever event. This comes from the tree model. You will need to alert the tree's model that you have changed a node or two. Read the documentation.

  • Strange Jtree behaviour

    I have a very strange behavior using a jtree.
    This tree has a structure like this:
    A
    |.\
    B.C
    |....\
    E...E
    |......\
    F.....F
    |........\
    G.......G
    Notice that equals letters are referred to the same viewobject row,
    I begin opening the tree from the root, when I open both 'E' nodes, some strange things happens,
    for example when I open 'G' all the right branch collapses, then if I open 'G' on the left, all the Jtree
    is automatically closed, even more when I re-open node 'E' (on the right) , also the left branch is
    automatically opened.
    I don't know what's the problem.
    Can anyone help me ?
    Thanks
    Massimo Marolda

    You're not the only one. I'm having difficulties with my JTree's as well (the ones with a JClient binding anyway). I'm keeping my fingers crossed that the new JDev/BC4J 9.0.4 will address these issues.

Maybe you are looking for

  • Report for outstanding invoice/ collections report

    How could we get a report on all the outstanding invoice for a customer based on regions. i.e One customer is serviced across the US. the client needs to get a report on all outstanding invoices based on regions. Any suggestions??

  • Is there a way to prevent MacOS from initializing second hard disk

    My second hard disk (using optibay slot) is a TrueCrypt encrypted backup disk of critical information (this is company policy). Because of this encryption, the second hard disk is not recognized and mounted "properly", and on starting up the dialog b

  • I have problem login to you tube built in

    I have problem login to youtube built in in ipad1 3.2 upgraded to 5.1.1, it simply do not get in rather in pc logged in without problems well? may install new you tube app not built in but stand alone or it can not done?

  • CRM_SURVEY_SUITE, make survey available ouside your lan

    Hi, We would like to  run and analyze an E-Mail Campaign with a Survey. We had create the survey and generate the url for it , according https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/4057. [original link is broken] [original link is broken] [

  • Stolen Blackberry - email?

    My old Blackberry was stolen, but I deactivated the old SIM card and made a duplicate of it, with my carrier. I bought a new Blackberry as a replacement but I can't seem to set up the personal email account with it as the option for it doesn't appear