DnD with JTree

Hi All,
I am creating two JTree ojects and registering it for DnD by calling method setDragEnabled(true). I created Class that extends from TransferHandler which contains all the required method including importData(). I have also created class for Transferable. But when i try to perform drag from one tree and drop it on another tree it is not working, but if I do it on the same tree it is working fine which I don't want to do. Here are the code snippets that create tree object and initialization.
JPanel panel = new JPanel();
JTree onTree = new JTree(new Vector());
onTree.setCellRenderer(new MyTreeCellRenderer());
onTree.setShowsRootHandles(true);
transferHandler1 = new MyTransferHandler();
onTree.setTransferHandler(transferHandler1);
onTree.setDragEnabled(true);
MyObjectJB myObj = (MyObjectJB) createData();
AdPlanningTreeNode root = new AdPlanningTreeNode(spot);
AdPlanningTreeNode spotNode = constructSubTree(root, spot);
JTree offTree = new JTree(root);
offTree.setCellRenderer(new DisplayTreeCellRenderer());
offTree.setShowsRootHandles(true);
transferHandler2 = new DisplayTransferHandler();
offTree.setTransferHandler(transferHandler2);
offTree.setDragEnabled(true);
AdPlanningJScrollPane offScroller = new AdPlanningJScrollPane(offTree);
AdPlanningJScrollPane onScroller = new AdPlanningJScrollPane(onTree);
panel.add(offScroller);
panel.add(onScroller);Here is code in importData() method of MyTransferHandler.
public boolean importData(JComponent comp, Transferable t) {
boolean isImported = false;
try {
     if (!canImport(comp, t.getTransferDataFlavors())) {
          System.out.println("MyTransferHandler.importData ; can not import");
          return false;
     JTree targetTree = (JTree) comp;
     TreePath parentPath = targetTree.getSelectionPath();
     MyTreeNode parentNode = null;
     DefaultTreeModel model = (DefaultTreeModel) targetTree.getModel();
     MyObject item = (MyObject) DeepCopyUtil.createDeepCopy(t.getTransferData(SUPPORTED_FLAVORS));
     MyTreeNode node = new MyTreeNode((MyObjectJB) item);
     if (parentPath == null) {
          model.setRoot(node);
          targetTree.setSelectionRow(0);
          targetTree.repaint();
     else {
          parentNode = (MyTreeNode) parentPath.getLastPathComponent();
          model.insertNodeInto(node, parentNode, 0);
     isImported = true;
catch (UnsupportedFlavorException e) {
     e.printStackTrace();
     return false;
catch (IOException e) {
     e.printStackTrace();
     return false;
catch (Exception e) {
     e.printStackTrace();
     return false;
System.out.println("DisplayTransferHandler.importData completed");
return isImported;
One important thing is after dragging and importData method calls
model.setRoot(node), then model is showing change in data but not reflected in Tree.

Following link may help you understand: http://forums.java.net/jive/thread.jspa?threadID=9196

Similar Messages

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

  • Problem with JTree converting Node to string

    I have a problem that I cannot slove with JTree. I have a DefaultMutalbeTreeNode and I need its parent and convert to string. I can get its parent OK but cannot convert it to string.
    thisnode.getParent().toString() won't work and gives an exception
    thisnode.getParent() works but how do I convert this to string to be used by a database.
    Thanks
    Peter Loo

    You are using the wrong method to convert it to a String array.
    Try replacing this line:
    String[] tabStr = (String[])strList.toArray();
    With this line:
    String[] tabStr = (String[])strList.toArray( new String[ 0 ] );
    That should work for you.

  • How can I open a picture with Jtree

    hi,
    I want to write a Filemanagerprogramm with JTree, but how can I open it, after I clickt the .jpg or .png file. Thank you for your Tip!

    The java tutorial at http://java.sun.com/docs/books/tutorial/uiswing/misc/icon.html will tell you a lot of what you need to know.

  • Problems with JTree

    Hi,
         I have a few problems while working with JTree. Here is the detail:
    I get the name of the required file from JFileChooser and add it to the root node of JTree using
    root.add(new DefaultMutableTreeNode(fileName));
    The following happens.
    1) If I add it to root, it is not added(or shown,at least) there.
    2) if I add it to a child of root, then if the node is collapsed before the event, after the event when it is expanded fileName is there.
    3) However if it is expanded before adding the fileName,the fileName is not added (or not shown).
    4) Further if I add another file(whether the node is collapsed or expanded) it is also not shown, means that it works only once during the life-time of the application.
    5) I have used JFrame and call repaint() for both the JFrame and JTree but the problem is still there.
         Please help me in solving this problem.
    Thanks in advance,
    Hamid Mukhtar,
    [email protected]
    H@isoft Technologies.

    Try doing this...
    tree.getModel().reload(node)
    node here is the node to which a new node is added

  • Display File System With JTree

    Greeting,
    Are there any suggestions or example which is about displaying file system with JTree??
    Thx Advanced

    Just create tree model from your filesystem.
    If you like to have fancier look, you may also
    create renderer which would show
    appropriate icons.
    Look to classes
    DefaultMutableTreeNode
    DefaultTreeModel
    ( all in the javax.swing.tree )

  • Autoscroll behavior during DnD in JTree, 1.4 vs 1.6

    The following code compiles under both Java 1.4 and Java 1.6. I'm wondering if anyone knows why the following actions cause different behaviors between the two versions:
    1. When the frame opens, you should see a fully-expanded tree (which, because of the small size, causes a vertical scrollbar to appear).
    2. Make a drag-and-drop gesture on the first child node ("blue"), and attempt to cause the tree to scroll down so you can drop it on the last parent node ("food").
    Under 1.6, the tree scrolls nicely as you hold the DnD gesture.
    Under 1.4, the tree does not scroll. I had some hope JTree.setAutoscrolls(true) would help, but it did not.
    Any suggestions how to get 1.4 to behave the way 1.6 does?
    Thanks for your time.
    import javax.swing.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import java.util.Enumeration;
    public class AutoScroll14 extends JFrame {
        public static void main(String[] args) {
            new AutoScroll14();
        public AutoScroll14() throws HeadlessException {
            super("AutoScroll 1.4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            public boolean importData(JComponent comp, Transferable t) {
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return false;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return false;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return true;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    return new StringTransferable(toTransfer);
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { localStringFlavor };
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;

    I added the class "TreeDropTarget".
    "TreeDropTarget" extends the class "DropTarget", which implements the interface "DropTargetListener".
    DropTargetListener has a few methods, that are called automatically by Swing during drag operation
    (dragOver, dragExit, drop). So we can implement "autoscroll", as well as "automatic node expansion".
    With "automatic node expansion", a collapsed node will be expanded,
    so that its children become visible and we can do a drop on them:
    package demo;
    * AutoScroll.java
    * source level 1.4
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.io.*;
    import java.util.*;
    public class AutoScroll extends JFrame {
        public static void main(String[] args) {
            new AutoScroll();
        public AutoScroll() throws HeadlessException {
            super("AutoScroll " + System.getProperty("java.version"));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            tree.setDropTarget(new TreeDropTarget());//<----------------------
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private AutoScroll.MyTransferHandler.StringTransferable transferable;
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            protected void exportDone(JComponent comp, Transferable t, int action) {
                if (t == null) {
                    t = transferable;
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    transferable = new StringTransferable(toTransfer);
    return transferable;
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[]{localStringFlavor};
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;
    class TreeDropTarget extends DropTarget {
    public TreeDropTarget() {
    super();
    public void dragOver(DropTargetDragEvent dtde) {
    JTree tree = (JTree) dtde.getDropTargetContext().getComponent();
    Point loc = dtde.getLocation();
    updateDragMark(tree, loc);
    autoscroll(tree, loc);
    super.dragOver(dtde);
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTree tree, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = tree.getVisibleRect();
    Rectangle inner = new Rectangle(
    outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(
    cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    tree.scrollRectToVisible(scrollRect);
    public void updateDragMark(JTree tree, Point location) {
    int row = tree.getRowForPath(tree.getClosestPathForLocation(location.x, location.y));
    TreePath path = tree.getPathForRow(row);
    if (path != null) {
    markNode(tree, location);
    private void markNode(JTree tree, Point location) {
    TreePath path = tree.getClosestPathForLocation(location.x, location.y);
    if (path != null) {
    if (lastRowBounds != null) {
    Graphics g = tree.getGraphics();
    g.setColor(Color.white);
    g.drawLine(lastRowBounds.x, lastRowBounds.y,
    lastRowBounds.x + lastRowBounds.width, lastRowBounds.y);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    private Rectangle lastRowBounds;
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Problem with Jtree to xml tranform..how to set/get parent of a node?

    Hi,
    I am trying to develop xml import/export module.In import wizard, I am parsing the xml file and the display it in Jtree view using xml tree model which implements TreeModel and xml tree node.I am using jaxp api..
    It is workin fine.
    I got stuck with removal of selected node and save it as a new xml.
    I am not able to get parent node of selected node in remove process,itz throwing null.I think i missed to define parent when i load treemodel.Plz help me out..give some ideas to do it..
    thanks
    -bala
    Edited by: r_bala on May 9, 2008 4:44 AM

    there's no way anyone can help you without seeing your code.

  • Problem with JTree while expanding/collapsing a node

    Hi,
    I'm using a JTree for displaying the file system.
    Here, i want that whenever a node get expanded,
    it should show the latest files/directories under that node.
    Now, what i'm doing is, getting all the files/dir's using files.listFiles(),
    under that node and then creating a new node and adding it to parent (all in expand() method).
    But, now the problem is, while doing this whenever the parent node get expanded its adding all the latest files/dirs into the previous instance
    resulting the same file/dir is displaying twice,thrice.. and so on, as that node is expanded and collapsed.
    i tried removeAllChildren() in collapse() method but then that node is notexpanding at all .
    Can anybody help me please...
    i got stuck b'coz of this only.
    Thanks...

    Now what i'm doing is every time expand() get called,
    i'm comparing all the children of that node in the
    current instance with all the children present in the
    file system (because there is a possibility that some
    file/dir may be added or deleted)
    is this the right wy or not?it certainly is not wrong, but as usual, there is more than 1 way to implement this...
    b'coz right now i'm getting all the files/dirs that
    are newly added but facing some problem if somebody
    deletes a file/dir.
    i'm still trying to get the solutionthen you should not just compare all the children of the node with the files/dirs but also the other way round. compare the files/dirs with the children to determine if the file/dir still exists and if not remove the node.
    or you could check if the file which a node represents exists and if not remove the node.
    thomas

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Problem with jtree selection

    Hi all,
    I've got a JTree that represents a sort of data that I'm going to change dynamically in my application. I'd like to reset the selection of the user to the leaf she has selected before the change to the tree structure.
    First of all my tree uses DefaultMutableTreeNode to build each node, and each DefaultMutableTreeNode contains a SingleKeyValue object, that is a key-value object (two strings) and that has an hashcode defined as follows:
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         public int hashCode() {
              return this.key.hashCode();
         I hope the hashcode can help me finding the right object even when its value changes (but the key is the same). The construction of the tree is the following:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("The root");
    // iterate and build each node
    SingleKeyValue object = new SingleKeyValue("key","value");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(object);
    root.add(node);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree  tree = new JTree(model);             
                so the tree is associated to a DefaultTreeModel. Then, when I need to change something in the tree I rebuild the tree and all leafs (with the SingleKeyValues) and rebuild the model:
              TreeModel treeModel = this.myTree.getModel();
              TreeSelectionModel selectionModel = this.myTree.getSelectionModel();
              DefaultTreeModel defaultTreeModel = null;
              DefaultTreeSelectionModel defaultTreeSelectionModel = null;
              TreePath selectedPath = null;
              TreeNode root = null;
              Logger.info("SimpleTreePanel.refreshDatabaseView: treemodel "+treeModel + " selectionModel " + selectionModel);
              if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
                   defaultTreeModel = (DefaultTreeModel) treeModel;
                   root = this.getRoot();
                   // get the selection
                   if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                        defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                        selectedPath = defaultTreeSelectionModel.getSelectionPath();
                        Logger.warn("Selection path of the tree: "+selectedPath);
                   // rebuild the tree
                   defaultTreeModel.setRoot(root);
                   // set the selected element
                   defaultTreeSelectionModel.setSelectionPath(selectedPath);The problem is that after the above code the tree is all closed, no leaf are selected. I guess the problem is with the SingleKeyValueObject because I've tried the default model and it works with, for example, simple strings. Any idea about?
    Thanks,
    Luca

    Here's a complete test program that creates a few SingleKeyValue objetcs (objects with a key and a description) and that then places them into a JTree using the DefaultMutableTreeNode. After that, the selection of user is took and one node is changed, but while the selection is working, the reload/refresh of the tree is not.
    Any idea about how to work on it?
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         // constants related to the type of the table this object refers to
         public static final String COMPETENCE = "competenza";
         public static final String FAMILY            = "famiglia_competenza";
         public static final String ROLE              = "ruolo";
         public static final String PROVINCE      = "provincia";
         public static final String KNOWLEDGE  = "titolo_studio";
         public final static String OBJECTIVE      = "obiettivo";
         public final static String PERSON         = "persona";
         public SingleKeyValue( String key, String value, String table){
              super();
              this.key = key;
              this.value = value;
              this.SQLTable = table;
          * @return the key
         public final String getKey() {
              return key;
          * @param key the key to set
         public final void setKey(String key) {
              this.key = key;
          * @return the value
         public final String getValue() {
              return value;
          * @param value the value to set
         public final void setValue(String value) {
              this.value = value;
          * Shows this element.
         public String toString(){
              String ret;
              if( this.showKey ){
                   ret =  this.label + this.key +" { "+ this.value +" }";
              else
                   ret = this.label + this.value;
              // trim the string
              if( ret.length() > this.maxLength )
                   return ret.substring(0 , this.maxLength);
              else
                   return ret;
          * The hash code of this object is the hash code of the key.
          * @return the hash code of the key of the object
         public int hashCode() {
              return this.key.hashCode();
          * Returns true if the object passed is a single key value equals (i.e., with the same key) of this one.
         public boolean equals(Object o){
              if( o== null || (! (o instanceof SingleKeyValue) ) )     return false;
              else
                   return (this.hashCode() == o.hashCode());
         public static void main(String argv[]) throws Exception{
             SingleKeyValue skv1 = new SingleKeyValue("Key1","Description1", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv2 = new SingleKeyValue("Key1a","Description1a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv3 = new SingleKeyValue("Key1b","Description1b", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv4 = new SingleKeyValue("Key2","Description2", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv5 = new SingleKeyValue("Key2a","Description2a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv6 = new SingleKeyValue("Key2b","Description2b", SingleKeyValue.COMPETENCE);
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
             DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(skv1);
             DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(skv2);
             DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(skv3);
             DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(skv4);
             DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(skv5);
             DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(skv6);
             rootNode.add(node1);
             node1.add(node2);
             node1.add(node3);
             rootNode.add(node4);
             node4.add(node5);
             node4.add(node6);
             JTree tree = new JTree(rootNode);
             JFrame f = new JFrame("Tree try");
             f.add( new JScrollPane(tree) );
             f.setSize(300,300);
             f.setVisible(true);
             System.out.println("Please select a node within 10 seconds");
             Thread.sleep(10000);
             // now get the user selection
         TreeModel treeModel = tree.getModel();
         TreeSelectionModel selectionModel = tree.getSelectionModel();
         DefaultTreeModel defaultTreeModel = null;
         DefaultTreeSelectionModel defaultTreeSelectionModel = null;
         TreePath selectedPath = null;
         TreeNode root = null;
         if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
              defaultTreeModel = (DefaultTreeModel) treeModel;
              // get the selection
              if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                   defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                   selectedPath = defaultTreeSelectionModel.getSelectionPath();
              // rebuild the tree
              node1.setUserObject(new SingleKeyValue("key20","key changed",SingleKeyValue.FAMILY));
              defaultTreeModel.reload();
              // set the selected element
              defaultTreeSelectionModel.setSelectionPath(selectedPath);
    }

  • Problem with JTree.isExpanded()

    Working with a JTree, I encountered into a strange behavior - I hope someone could explain me...
    For exporting a tree I need the information whether nodes are expanded or not.
    The first strange thing is that the root always seems to be collapsed - but this I can handle somehow.
    The problem is, that a expanded node containing a leaf, is reported as collapsed - but it is not. Why?
    Here the output of a expand-checking method, which prints the state of the node and its parents.
    (the "+" indicates a expanded node, the "-" indicated a collapsed node)
    + - Abasdf
    + - EP/asdf
    + - - Prosadf
    + - - - Altasdf
    + - - - - V1sadf
    + - - - - - 059asdf
    + - - - - - - 059asdf
    + - - - - - - + 059asdf
    + - - - - - - + + this_is_a_leafWhy is the expanded node containing the leaf reported as collapsed?
    I'm using the following for checking if a node is expanded:
    view.isExpanded(node.getIndex())I also tried this - with the same wrong result:
    view.isExpanded(view.getPathForRow(node.getIndex()))Any hint is highly appretiated.

    I was not able to reproduce your problemimport javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.util.Random;
    import java.util.Enumeration;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class HamsterChipsyTest extends JPanel {
         private static final Random RANDOM = new Random(System.currentTimeMillis());
         private JTree theTree;
         private DefaultTreeModel theTreeModel;
         private DefaultMutableTreeNode theRoot;
         public HamsterChipsyTest() {
              super(new BorderLayout());
              theRoot = createRandomNode();
              addNodes(theRoot, 0, 2);
              theTreeModel = new DefaultTreeModel(theRoot);
              theTree = new JTree(theTreeModel);
              add(new JScrollPane(theTree), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("dump nodes' extension state") {
                   public void actionPerformed(ActionEvent e) {
                        dumpExtensionState(theRoot);
              }), BorderLayout.NORTH);
         private void dumpExtensionState(DefaultMutableTreeNode aTreeNode) {
              TreeNode[] path = aTreeNode.getPath();
              for (int i = 0; i < path.length; i++) {
                   System.out.print('-');
              System.out.println(" " + aTreeNode.getUserObject().toString() + " " + theTree.isExpanded(new TreePath(path)));
              Enumeration children  = aTreeNode.children();
              while(children.hasMoreElements()) {
                   DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
                   dumpExtensionState(child);
         private static void addNodes(DefaultMutableTreeNode aParent, int aCurrentDepth, int aMaxDepth) {
              if (aCurrentDepth >= aMaxDepth) return;
              int nodeCount = RANDOM.nextInt(3);
              for (int i = 0; i < nodeCount + 1; i++) {
                   DefaultMutableTreeNode child = createRandomNode();
                   aParent.add(child);
                   addNodes(child, aCurrentDepth + 1, aMaxDepth);
         private static DefaultMutableTreeNode createRandomNode() {
              char[] chars = new char[5];
              for (int i = 0; i < chars.length; i++) {
                   chars[i] = (char)('a' + RANDOM.nextInt(26));
              return new DefaultMutableTreeNode(new String(chars));
         public static void main(String[] args) {
              final JFrame frame = new JFrame(HamsterChipsyTest.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new HamsterChipsyTest());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }

  • Focus Problem with JTree and Menus

    Hi all,
    I have a problem with focus when editing a JTree and selecting a menu. The problem occurs when the user single clicks on a node, invoking the countdown to edit. If the user quickly clicks on a menu item, the focus will go to the menu item, but then when the countdown finishes, the node now has keyboard focus.
    Below is code to reproduce the problem. Click on the node, hover for a little bit, then quickly click on the menu item.
    How would I go about fixing the problem? Thanks!
    import java.awt.Container;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class MyTree extends JTree {
         public MyTree(DefaultTreeModel treemodel) {
              setModel(treemodel);
              setRootVisible(true);
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JMenuBar bar = new JMenuBar();
              JMenu menu = new JMenu("Test");
              JMenuItem item = new JMenuItem("Item");
              menu.add(item);
              bar.add(menu);
              frame.setJMenuBar(bar);
              Container contentPane = frame.getContentPane();
              contentPane.setLayout(new GridLayout(1, 2));
              DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("Root");
              root1.add(new DefaultMutableTreeNode("Root2"));
              DefaultTreeModel model = new DefaultTreeModel(root1);
              MyTree tree1 = new MyTree(model);
              tree1.setEditable(true);
              tree1.setCellEditor(
                   new ComponentTreeCellEditor(
                        tree1,
                        new ComponentTreeCellRenderer()));
              tree1.setRowHeight(0);
              contentPane.add(tree1);
              frame.pack();
              frame.show();
    import java.awt.FlowLayout;
    import java.util.EventObject;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    public class ComponentTreeCellEditor
         extends DefaultTreeCellEditor
         implements TreeCellEditor {
         private String m_oldValue;
         private TreeCellRenderer m_renderer = null;
         private DefaultTreeModel m_model = null;
         private JPanel m_display = null;
         private JTextField m_field = null;
         private JTree m_tree = null;
         public ComponentTreeCellEditor(
              JTree tree,
              DefaultTreeCellRenderer renderer) {
              super(tree, renderer);
              m_renderer = renderer;
              m_model = (DefaultTreeModel) tree.getModel();
              m_tree = tree;
              m_display = new JPanel(new FlowLayout(FlowLayout.LEFT));
              m_field = new JTextField();
              m_display.add(new JLabel("My Label "));
              m_display.add(m_field);
         public java.awt.Component getTreeCellEditorComponent(
              JTree tree,
              Object value,
              boolean isSelected,
              boolean expanded,
              boolean leaf,
              int row) {
              m_field.setText(value.toString());
              return m_display;
         public Object getCellEditorValue() {
              return m_field.getText();
          * The edited cell should always be selected.
          * @param anEvent the event that fired this function.
          * @return true, always.
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
          * Only edit immediately if the event is null.
          * @param event the event being studied
          * @return true if event is null, false otherwise.
         protected boolean canEditImmediately(EventObject event) {
              return (event == null);
    }

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

Maybe you are looking for

  • Power BI Scheduling Error

    Hi, I am getting the following scheduling error for the report which I ceated using Power Query and publish on O365. If anyone has any insight on the same please help. I am trying to pull the data from Sharepoint list into excel for the report Refres

  • Semitransparent Panel on fullscreened jPanel

    help me to make the AircraftCockpit a senitransparent jPanelimport java.awt.Color; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import java.aw

  • Toshiba laptop to TV -trouble with the sound

    Hi, i've hooked up my laptop (running Windows 7) to my TV with RGA and audio cables. The picture is fine and the sound comes through the TV. The trouble is that I cannot get the sound to stop on the laptop without is also stopping on the TV.  Would a

  • Viewsonic VX2453MH-LED Display Works, but no sound from monitor

    I'm using 15" MBP (early 2011), OS X Lion, and I saw earlier threads about this disaply not working (vertical bars).  I figured that part out, but am having trouble with no sound coming from the built-in speakers.  I have a Moshi HDMI adapter and Vie

  • Load problome

    Hi Experts When i am loading deltas i am getting this error please help me Systax error in RSCDELTA Could any body help ????? thanls Sudha