Multiple JTrees

Hi everybody!
I've got to create something very similar to a file commander - something like dos NC or linux MC. The difference is there are my objects - called "resources" - instead of files. I've created a JFrame with two separate JPanels, each of them handling separate JTree.
The problem is when I create o DefaultMutableTreeNode with the same user object for both JTrees, the node is shown only on the first of them. When I switch the order of adding folders, the node is visible only on the latter one.
Can anybody help me? Thanx!

Hi Pipzeno! I've just solved problem on my own. I've found a stupid mistake in my code. The method addFolders(Vector folders) in the class representing a JTree was removing all objects from the given Vector. So, the second JTree was given an empty Vector as the parameter.
Anyway, Merry X-mas! :))))

Similar Messages

  • How can I manage multiple JTrees by establishing a link between them?

    Hi guys,
    I have a program that load 2 JTree in a separate panel by JSplitPane.
    Now what I want to do is that if I click on a node in one of these trees in one SplitPane, I want the other tree to do something correspondingly in another SplitPane.
    I know I can make the game big as 2 threads, but I try to solve it in a minimum solution.
    Is there any hints and examples?
    Thanks
    Michael

    Hi, again,
    I have 2 JTree objects. I wrote a JTree node selection listener extends the MouseAdaptor to respond to mouse click in my first JTree object.
    The listener works fine and can return me what I need, for example return me the node I clicked and some associated nodes which located in my second tree.These 2 trees locate in separating splitPane in a GUI window.
    My idea is let the second tree be updated spontaneously upone the clicking in my first JTree node..How could I inform the second tree about my mouse event in the first tree?
    Thanks to your replies.

  • Render the same model in multiple ways for several components

    I am faced by the problem explained in the subject.
    Getting more specific I have two jtrees that should share the same model/nodes and display them in two different ways (different icons, different popups...)
    I have to cut & paste nodes in one of the trees while I use the other to set some properties in a convenient way so it would be really nice if there was a way to have only one data model so that the two jtrees would be synchronized (not easy to do otherwise...)
    So basically I'd like to change the renderer on fly depending on which "view" of the model I am rendering, I need also to keep the selection separated otherwise things would get really out of hand.
    Any ideas?

    You have described the solution in your question.
    One TreeModel can be set to multiple JTrees. I am more familure with Tables, but I am pretty sure the same holds true to trees.
    The renderer can be set per tree and can show any aspect of the data node you wish.
    Just make sure that all your data manipulations are done in the model. Meaning DON'T manually add children to a tree node, instead use the manipulation methods from DefaultTreeModel:
    insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index)
    removeNodeFromParent(MutableTreeNode node)Or if you implement your own tree model, make sure to inform the TreeModelListener's of all changes.

  • JTree multiple nodes selection problem !

    I can not make my JTree to be in multiple node selection mode.
    I have custom tree model and tree node class, the tree model class
    implements javax.swing.tree.TreeModel, and the tree node is an ordinary
    Java object.
    In this setting, my JTree is always in single selection mode.
    I have tried set the selection model after the JTree has initialized, and
    it didn't work.
    What I missed in TreeModel implementation ? Or should my tree node class
    also implements javax.swing.tree.TreeNode ?
    Don't tell me just call
    xxtree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    It didn't work.

    Just in case anyone wants to know, I did find the magic number of files, and what the problem is. I talked with tech suppot at Adobe, and they know the problem exists, but won't fix it. I did put in a request in the "Request a Feature" form. Read on:
    The magic number is 40 Canon 1Ds Mark III Raw files, and clicking on three or more keywords. The key to not having the numbers of keywords counted incorrectly in the filter pane is to click on the keywords as fast as you can before it starts to write to the metadata. If you click on each keyword one at a time, and wait about a second or more between selecting the keywords, then the counts in the filter panel for the number of keywords is not correct in relation to the number of files that you have chosen to apply keywords to. The cure for this is to click as many keywords as possible as fast as you can before the software starts incorporating the keywords into the metadata.
    I would suggest to Adobe, that a nice feature would be that one could click on as many keywords as one would want, to as many files one would want, and then have a button or icon that would enable one to then apply all the keywords at once, instead of applying them as you click them as it is now. I also would love it if Adobe fixed it now instead of waiting to fix it in the version of CS5. Someone on Adobe's support line told me that Adobe would rather wait to put this into the CS5 version than fix it now. I don't think that is right, but heck, I am only one guy who depends on this software to provide images keyworded to my clients in a timely manner. I would never run my business like this Adobe. If there is a problem, and there is, please fix it now, or give me some of my money back since your product has a design flaw that is having a negative impact in my ability to to my job and run my business.
    Thanks!
    Daniel Root
    Portland, OR

  • Selcting Multiple  CheckBoxe in a JTREE without holding CTRL / SHIFT

    HI,
    My JTree is having JCheckBOxes as nodes .... Now the problem is i want to select multiple nodes (checkboxes) with out holding CTRL/SHIFT key .
    Please help regarding this issue ..
    The code of my renderer class is as below:
    * MyTreeRendered.java
    * Created on April 27, 2006, 7:42 PM
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class MyTreeRendered extends DefaultTreeCellRenderer  {
        private JCheckBox cb ;
        /** Creates a new instance of MyTreeRendered */
        public MyTreeRendered() {
        public Component getTreeCellRendererComponent(
                            JTree tree,
                            Object value,
                            boolean sel,
                            boolean expanded,
                            boolean leaf,
                            int row,
                            boolean hasFocus){
           if(cb == null) {
               cb = new JCheckBox();
               cb.setBackground(tree.getBackground());
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
           cb.setText(node.getUserObject().toString());
           cb.setSelected(sel);
           return cb;
    }

    These are the methods which seem to define that behaviour:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicTreeUI.html#isToggleSelectionEvent(java.awt.event.MouseEvent)
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicTreeUI.html#isMultiSelectEvent(java.awt.event.MouseEvent)
    You'd have to write your own TreeUI and override them.

  • Create multiple root in a JTree??????very urgent..pl

    hello
    i have a jtree which takes a defaultMutableTreenode as its parameter.
    My problem is that i have to create multiple root.
    and what i get with this is a single root at the top.
    what is the solution for creating multiple roots in a jtree.
    pl. help its very urgent
    thanx
    hussain

    Hello Hussain,
    I found in the sourcecode of JTree the following constructor which might is be helpful for you:
    * Returns a <code>JTree</code> with each element of the specified
    * <code>Vector</code> as the
    * child of a new root node which is not displayed. By default, the
    * tree defines a leaf node as any node without children.
    * @param value a <code>Vector</code>
    * @return a <code>JTree</code> with the contents of the
    *          <code>Vector</code> as children of the root node
    * @see DefaultTreeModel#asksAllowsChildren
    public JTree(Vector value) {
    this(createTreeModel(value));
    this.setRootVisible(false);
    this.setShowsRootHandles(true);
    Greetings
    Helmut

  • How to allow multiple selection of nodes in a JTree

    How to allow multiple selection of nodes in a JTree ?
    Thanks
    S.Satish

    By default when you create new instance og JTree the selection model is multiple selection. And if you want to change it you use next:
    tee.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Hope will help!

  • Images and multiple lines in JTree

    I have a JTree and would like to display more details about certain nodes than can be seen in a single line, and perhaps images in some cases. What I was hoping I could do was instantiate DefaultMutableTreeNode with a JPanel that looked the way I wanted, but it turns out DefaultMutableTreeNode just uses the toString method of the object as the string it displays. Is there any way to do this? Here's an example of what I want (if images will display here.. if not, here's the link: http://www.enginuity.org/files/jtree_labels_157.gif )

    DefaultMutableTreeNode is only a model class, it does not know or care how the data is displayed (you could use DefaultMutableTreeNode without ever displaying the data in a JTree). What you need is a TreeCellRenderer (although I'm not sure you can set row height with that). This allows you to instruct the JTree to query you for a component to display for each cell of the tree. This component might be a JPanel with whatever you want in it.
    You should check this section of the JAVA Tutorial for more details: http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    If what you need is to display a multiple columns for each node (a so-called TreeTable) then the matter is more complicated. But I found an article from Sun that describes how to write such a thing (I don't have the link handy).
    Message was edited by:
    A.Cristescu

  • Multiple Selection on JTree without holding down [CTRL] or [SHIFT]

    I need an example about how make multiple selection on JTree without holding down [CTRL] or [SHIFT].
    my JTree contains JCheckBox in any nodes, but I can't select two or more checkBox in time without holding down [CRTL] or [SHIFT].
    thanks for help.
    Jose A.

    I did this a few years ago so my newbiness is going to show through a bit, but I'm too lazy to update it.import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class Test3 extends JFrame {
      JTree jt = new JTree();
      MultiTreeSelectionModel mtsm = new MultiTreeSelectionModel(jt);
      JCheckBox multiCheck = new JCheckBox("Multi"),
          branchCheck = new JCheckBox("Branch");
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel content = (JPanel)getContentPane();
        multiCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mtsm.setMultiSelect(multiCheck.isSelected());
        branchCheck.setText("Branch");
        branchCheck.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
                mtsm.setBranchSelect(branchCheck.isSelected());
        JPanel jp = new JPanel();
        jp.add(multiCheck);
        jp.add(branchCheck);
        content.add(jp, BorderLayout.NORTH);
        ActionListener specialKeyListener =
            new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    MultiTreeSelectionModel.keyModifiers = evt.getModifiers();
        KeyStroke keyStroke;
        for (int i = 0; i < keys.length; i++) {
            keyStroke = KeyStroke.getKeyStroke(keys[0], 0, true);
    content.registerKeyboardAction(specialKeyListener, keyStroke,
    JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    keyStroke = KeyStroke.getKeyStroke(keys[i][0], keys[i][1], false);
    content.registerKeyboardAction(specialKeyListener, keyStroke,
    JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    jt.setSelectionModel(mtsm);
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    setSize(300, 300);
    setVisible(true);
    public static void main(String[] args) { new Test3(); }
    private static int[][] keys = {{KeyEvent.VK_CONTROL, ActionEvent.CTRL_MASK},
    {KeyEvent.VK_SHIFT, ActionEvent.SHIFT_MASK},
    {KeyEvent.VK_ALT, ActionEvent.ALT_MASK}};
    class MultiTreeSelectionModel extends DefaultTreeSelectionModel {
    static int keyModifiers;
    private boolean branchSelect, multiSelect;
    private JTree tree;
    private TreePath[] savePaths;
    MultiTreeSelectionModel(JTree Tree) {
    tree = Tree;
    setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    private boolean isSelected(TreePath Path) {
    return tree.isPathSelected(Path) && (keyModifiers & KeyEvent.SHIFT_MASK) == 0;
    private boolean branchSelect() {
    return branchSelect || ((keyModifiers & KeyEvent.ALT_MASK) != 0);
    public void addSelectionPaths(TreePath[] paths) {
    if (branchSelect()) paths = getAllPaths(paths);
    super.addSelectionPaths(paths);
    public void removeSelectionPaths(TreePath[] paths) {
    if (branchSelect()) paths = getAllPaths(paths);
    super.removeSelectionPaths(paths);
    public void setSelectionPaths(TreePath[] paths) {
    if (branchSelect()) {
    paths = getAllPaths(paths);
    if (paths != null && paths.length > 0 && isSelected(paths[0])) {
    super.removeSelectionPaths(paths);
    } else if (multiSelect) super.addSelectionPaths(paths);
    else super.setSelectionPaths(paths);
    protected TreePath[] getAllPaths(TreePath[] paths) {
    if (paths == null || paths.length == 0) {
    return paths;
    Vector vector = new Vector();
    DefaultMutableTreeNode treeNode, thisNode;
    for (int i = 0; i < paths.length; i++) {
    if (paths[i] != null) {
    thisNode = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
    Enumeration enumeration = thisNode.preorderEnumeration();
    while (enumeration.hasMoreElements()) {
    // add all descendants to vector
    treeNode = (DefaultMutableTreeNode) enumeration.nextElement();
    TreePath treePath = new TreePath(treeNode.getPath());
    vector.add(treePath);
    int i = vector.size();
    TreePath[] allpaths = new TreePath[i];
    for (int j = 0; j < i; j++) {
    allpaths[j] = (TreePath) vector.elementAt(j);
    return allpaths;
    protected void setMultiSelect(boolean b) { multiSelect = b; }
    protected boolean isMultiSelect() { return multiSelect; }
    protected void setBranchSelect(boolean b) { branchSelect = b; }
    protected boolean isBranchSelect() { return branchSelect; }
    protected void savePaths(TreePath Path) {
    TreePath[] tmpPaths = getSelectionPaths();
    if (tmpPaths == null) {
    savePaths = null;
    } else {
    int cnt = 0;
    for (int i = 0; i < tmpPaths.length; i++) {
    if (tmpPaths[i].isDescendant(Path)) {
    cnt++;
    savePaths = new TreePath[cnt];
    cnt = 0;
    for (int i = 0; i < tmpPaths.length; i++) {
    if (tmpPaths[i].equals(Path) || tmpPaths[i].isDescendant(Path)) {
    savePaths[cnt++] = tmpPaths[i];
    protected void restorePaths() {
    if (savePaths != null) {
    final DefaultTreeSelectionModel foo = this;
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {
    foo.setSelectionPaths(savePaths);

  • JTree - multiple selection doesn't highlight tree nodes

    I have a JTree which was working great with single selection of objects within it. Now i'm expanding this to work with multiple selected objects at the same time, but the objects are not visibly highlighted in the tree.
    I switched to using DISCONTIGUOUS_TREE_SELECTION, and using setSelectionPaths(TreePath[]) instead of setSelectionPath(TreePath). This works fine, except that the newly selected paths don't visually highlight any more (worked fine with single selection).
    I had thought that the RowMapper was the culprit, but the default VariableHeightLayoutCache seems to be in place and ok. What should i be checking to get this to work right?
    Thanks.

    /me beats forehead against the desk..
    TreePath selectionPath = new TreePath( entityNode.getPath() );
    NOT just
    TreePath selectionPath = new TreePath( entityNode );

  • How can create a JTree with cellRender is checkbox realized multiple selec

    How can create a JTree with cellRender is checkbox realized multiple selection function.thanks for every
    one's help.

    Hi,
    1. Create a value node in your context name Table and set its cardinality to 0:n
    2. Create 2 value attributes within the Table node name value1 and value2
    3. Goto Outline view> Right click on TransparentUIContainer>Apply Template> Select Table>mark the node Table and it's attributes.
    you have created a table and binded its value to context
    Table UI properties
    4.Set Selection Mode to Multi
    5.Set Visible Row Count to 5
    6.ScrollableColCount to 5
    In your implemetaion, you can add values to table as follow:
    IPrivate<viewname>.ITableElement ele = wdContext.nodeTable().createTableElement();
    ele.setValue1(<value>);
    ele.setValue2(<value>);
    wdContext.nodeTable().addElement(ele);
    The above code will allow you to add elements to your table node.
    Regards,
    Murtuza

  • Does JTree support multiple DnD?

    I'm working on an applet which displays a JTree tree, which has to support multiple DnD.
    i mean, user has to be capable of selecting several nodes at a time and drag all of them, dropping them into a target.
    Though i have asked about it, and somebody told me about it, the solution was with a JFrame, and all the examples which work and i've read, arre with JFrame.
    So i guess that maybe JTree does not support multiple DnD, and moreover, there is a website
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4165577
    in which someone says that, in fact, JTree does not support it. But it's and old page, so i want to know if at present, Jtree still has this debug.
    Thanks in advance!

    http://www.java-forum.org/de/viewtopic.php?p=139820#139820

  • JTree cut and paste multiple child and ancestor nodes not function correct

    Hello i'm creating a filebrowser for multimedia files (SDK 1.22) such as .jpg .gif .au .wav. (using Swing, JTree, DefaultMutableTreeNode)
    The problem is I want to cut and paste single and multiple nodes (from current node til the last child "top-down") which partly functions:
    single nodes and multiple nodes with only one folder per hierarchy level;
    Not function:
    - multiple folders in the same level -> the former order gets lost
    - if there is a file (MMed. document) between folders (or after them) in the same level this file is put inside one of those
    I tried much easier functions to cope with this problem but every time I solve one the "steps" the next problem appears...
    The thing I don't want to do, is something like a LinkedList, Hashtable (to store the nodes)... because the MMed. filebrowser would need to much resources while browsing through a media library with (e.g.) thousands of files!
    If someone has any idea to solve this problem I would be very pleased!
    Thank you anyway by reading this ;)
    // part of the code, if you want more detailed info
    // @mail: [email protected]
    import java.util.Enumeration;
    import javax.swing.*;
    import javax.swing.tree.*;
    // var declaration
    static Enumeration en;
    static DefaultMutableTreeNode jTreeModel, lastCopiedNode, dmt, insert, insertParent, insertSameFolder;
    static String varCut;
    static int index= 0;
    static int counter = 0;
    /* cut function */
    if (actionCommand.equals ("cut"))
         // get the selected node (DefaultMutableTreeNode)
         lastCopiedNode = (DefaultMutableTreeNode)  selPath.getLastPathComponent ();
         // get the nodes in an Enumeration array (in top- down order)
         en = dmt.preorderEnumeration();
         // the way to make sure if it is a cut or a copied node
         varCut = "cut";
    /* paste function */
    if (actionCommand.equals ("paste"))
    // node is cut
    if (varCut == "cut")
    // is necessary for first time same folder case
    insertParent = dmt;
    // getting the nodes out of the array
    while(en.hasMoreElements())
         // cast the Object to DefaultMutableTreeNode
         // and get stored (next) node
         insert = (DefaultMutableTreeNode) en.nextElement();
    // check if the node is a catalogue when getRepresentation()
    // is a function of my node creating class (to know if it is
    // a folder or a file)
    if (insert.getRepresentation().equals("catalogue"))
         // check if a "folder" node is inserted
         if (index == 1)
              counter = 0;
              index = 0;
         System.out.println ("***index and counter reset***");
         // the node is in the same folder
         // check if the folder is in the same hierarchy level
         // -> in this case the insertParent has to remain
         if (insert.getLevel() == insertParent.getLevel())
              // this is necessary to get right parent folder
              insertSameFolder = (Knoten) insert.getParent();
              jTreeModel.insertNodeInto (insert, insertSameFolder, index);
    System.out.println (">>>sameFolderCASE- insert"+counter+"> " + String.valueOf(insert) +
              "\ninsertTest -> " + String.valueOf(insertTest)
              // set insertParent folder to the new createded one
              insertParent = insert;
              index ++;
         else // the node is a subfolder
              // insertNode
              jTreeModel.insertNodeInto (insert, insertParent, index);
              // set insertParent folder to the new createded one
              insertParent = insert;
    System.out.println (">>>subFolderCASE- insertParent"+counter+"> " + String.valueOf(insertParent) +
              "\ninsertParent -> " + String.valueOf(insertParent)
              index ++;
    else // the node is a file
         // insertNode
         jTreeModel.insertNodeInto (insert, insertParent, counter);
         System.out.println (">>>fileCASE insert "+counter+"> " + String.valueOf(insert) +
         "\ninsertParent -> " + String.valueOf(insertParent)
    counter ++;
    // reset index and counter for the next loop
    index = 0;
    counter = 0;
    // reset cut var
    varCut = null;
    // remove the node (automatically deletes subfolders and files)
    dmt.removeNodeFromParent (lastCopiedNode);
    // if node is a copied one
    if varCut == null)
         // insert copied node the same way as for cut one's
         // to make it possible to copy more than one node
    }

    You need to use a recursive copy method to do this. Here's a simple example of the copy. To do a cut you need to do a copy and then delete the source.
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.*;
    import java.util.*;
    public class CopyTree extends JFrame
         Container cp;
         JTree cTree;
         JScrollPane spTree;
         DefaultTreeModel cModel;
         CNode cRoot;
         JMenuBar menuBar = new JMenuBar();
         JMenu editMenu = new JMenu("Edit");
         JMenuItem copyItem = new JMenuItem("Copy");
         JMenuItem pasteItem = new JMenuItem("Paste");
         TreePath [] sourcePaths;
         TreePath [] destPaths;
         // =====================================================================
         // constructors and public methods
         CopyTree()
              super("Copy Tree Example");
              addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent evt){System.exit(0);}});
              // edit menu
              copyItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuCopy();}});
              editMenu.add(copyItem);
              pasteItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuPaste();}});
              editMenu.add(pasteItem);
              menuBar.add(editMenu);
              setJMenuBar(menuBar);
              buildModel();
              cp = getContentPane();
              cTree = new JTree(cModel);
              spTree = new JScrollPane(cTree);
              cp.add(spTree, BorderLayout.CENTER);
              pack();
         static public void main(String [] args)
              new CopyTree().show();
         // =====================================================================
         // private methods - User Interface
         private void mnuCopy()
              sourcePaths = cTree.getSelectionPaths();
         private void mnuPaste()
              TreePath sp, dp;
              CNode sn,dn;
              int i;
              destPaths = cTree.getSelectionPaths();
              if(1 == destPaths.length)
                   dp = destPaths[0];
                   for(i=0; i< sourcePaths.length;i++)
                        sp = sourcePaths;
                        if(sp.isDescendant(dp) || dp.isDescendant(sp))
                             JOptionPane.showMessageDialog
                                  (null, "source and destinations overlap","Paste", JOptionPane.ERROR_MESSAGE);
                             return;
                   dn = (CNode)dp.getLastPathComponent(); // the node we will append our source to
                   for(i=0; i< sourcePaths.length;i++)
                        sn = (CNode)sourcePaths[i].getLastPathComponent();
                        copyNode(sn,dn);
              else
                   JOptionPane.showMessageDialog
                        (null, "multiple destinations not allowed","Paste", JOptionPane.ERROR_MESSAGE);
         // recursive copy method
         private void copyNode(CNode sn, CNode dn)
              int i;
              CNode scn = new CNode(sn);      // make a copy of the node
              // insert it into the model
              cModel.insertNodeInto(scn,dn,dn.getChildCount());
              // copy its children
              for(i = 0; i<sn.getChildCount();i++)
                   copyNode((CNode)sn.getChildAt(i),scn);
         // ===================================================================
         // private methods - just a sample tree
         private void buildModel()
              int k = 0;
              cRoot = new CNode("root");
              cModel = new DefaultTreeModel(cRoot);
              CNode n1a = new CNode("n1a");
              cModel.insertNodeInto(n1a,cRoot,k++);
              CNode n1b = new CNode("n1b");
              cModel.insertNodeInto(n1b,cRoot,k++);
              CNode n1c = new CNode("n1c");
              cModel.insertNodeInto(n1c,cRoot,k++);
              CNode n1d = new CNode("n1d");
              cModel.insertNodeInto(n1d,cRoot,k++);
              k = 0;
              CNode n1a1 = new CNode("n1a1");
              cModel.insertNodeInto(n1a1,n1a,k++);
              CNode n1a2 = new CNode("n1a2");
              cModel.insertNodeInto(n1a2,n1a,k++);
              CNode n1a3 = new CNode("n1a3");
              cModel.insertNodeInto(n1a3,n1a,k++);
              CNode n1a4 = new CNode("n1a4");
              cModel.insertNodeInto(n1a4,n1a,k++);
              k = 0;
              CNode n1c1 = new CNode("n1c1");
              cModel.insertNodeInto(n1c1,n1c,k++);
              CNode n1c2 = new CNode("n1c2");
              cModel.insertNodeInto(n1c2,n1c,k++);
         // simple tree node with copy constructor
         class CNode extends DefaultMutableTreeNode
              private String name = "";
              // default constructor
              CNode(){this("");}
              // new constructor
              CNode(String n){super(n);}
              // copy constructor
              CNode(CNode c)
                   super(c.getName());
              public String getName(){return (String)getUserObject();}
              public String toString(){return  getName();}

  • Ghost image for multiple selection in JTree while drag and drop.

    I am unable to create a Ghost image for drag and drop with in the JTree for multiple selection, i got some examples but all are for single selection ,
    Idea of creating buffered image is good , but unable to create it for multiple selection , tried a lot but got weird results.... can any body give me any clue about this , if got any example that will be fantastic.
    Thanks & Regards
    Sandeep Mandori

    sandeep_mandori wrote:
    I am unable to create a Ghost image for drag and drop with in the JTree for multiple selection, i got some examples but all are for single selection ,
    Idea of creating buffered image is good , but unable to create it for multiple selection , tried a lot but got weird results.... can any body give me any clue about this , if got any example that will be fantastic.
    Thanks & Regards
    Sandeep MandoriTry this:
        private TreePath[] dragPath;
        private BufferedImage[] image;
        private void createDragImage(JTree tree) {
            if (dragPath != null) {
                try {
                    image = new BufferedImage[dragPath.length];
                    for (int i = 0; i < dragPath.length; i++) {
                        Rectangle pathBounds = tree.getPathBounds(dragPath);
    TreeCellRenderer r = tree.getCellRenderer();
    DefaultTreeModel m = (DefaultTreeModel)tree.getModel();
    boolean nIsLeaf = m.isLeaf(dragPath[i].getLastPathComponent());
    MutableTreeNode draggedNode = (MutableTreeNode) dragPath[i].getLastPathComponent();
    JComponent lbl = (JComponent)r.getTreeCellRendererComponent(tree, draggedNode, false ,
    tree.isExpanded(dragPath[i]),nIsLeaf, 0,false);
    lbl.setBounds(pathBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    lbl.setOpaque(false);
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {}

  • Multiple Selection in JTree, Drag & Drop

    Hi everybody,
    I was wondering if anyone knows how to implement Multiple Selection Drag and Drop in a JTree. I know that there used to be a bug in jdk 1.3 that would allow it, but I suspect 1.4 fixed that. I've implemented Single-selection just fine, but I'm trying do Multiple selection by drawing a selection rectangle and selecting whatever nodes are contained within that rectangle. So far I've implemented it by adding a MouseListener to my JTree, finding which rows are intersected by the rectangle and calling addSelectionRow() to add the TreePaths.
    Is there an easier way to multiple selection now that the bug of 1.3(I hope) has been fixed?

    Okay, now I've implemented the changes in the DragGestureListener, DragSourceListener and DragTargetListener in order to make Multiple Selection possible, however I want to select multiple items the same way Windows Explorer does by:
    1. pressing the left-mouse button & dragging a "selection" rectangle which selects all the nodes contained within that rectangle.
    2. then drag and drop is accomplished by pressing one of the selected nodes and dragging it (along with it's other selected siblings) to the destination.
    In order to accomplish this I added into the Constructor of my JTree extending class this code:
    public class MyTree extends JTree {
    private static int x1, y1, x2, y2;
    public MyTree(DefaultMutableTreeNode rootNode){
    // Other Constructor stuff...
    this.addMouseMotionListener( new MouseMotionListener() {
    public void mouseDragged(MouseEvent e) {  
    x2 = e.getX();
    y2 = e.getY();
    repaint();
    public void mouseMoved(MouseEvent e){     }
    this.addMouseListener(new MouseAdapter(){
    boolean dontRelease = false;
    public void mousePressed( MouseEvent e){
    x1 = e.getX();
    y1 = e.getY();
    int[] rows = getSelectionRows();
    boolean dropSel = true;
    if (rows != null){
    for (int i = 0; i < rows.length; i++){
    Rectangle rect3 = getRowBounds(i);
    if (rect3.contains(x1, y1)){
    dropSel = false;
    dontRelease = true;
    if (dropSel){
    for (int i =0; i < rows.length; i++)
    removeSelectionRow(i);
    public void mouseReleased( MouseEvent e){
    x2 = e.getX();
    y2 = e.getY();
    repaint();
    if (dontRelease == false) {
    Rectangle rect2 = new Rectangle(Math.min(x1, x2),
    Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));
    int rowCount = getRowCount();
    for (int i = 1; i < rowCount; i++) {
    Rectangle rect3 = getRowBounds(i);
    if ((rect2.contains(rect3)) || (rect2.intersects(rect3))){
    addSelectionRow(i);
    dontRelease = false;
    repaint();
    The idea was that for every press of the mouse the 1st set of x,y coords. are taken to be the starting corner of the "selection" rectangle, and every point passed over while dragging would be the ending corner of the rectangle (so that in paintComponents, you could actually draw the rectangle).
    Once the mouse is released it will check to see if the selection rectangle had contained or intersected any of the rows (basically I find how many rows are being shown in the tree and go through each one to see if there is intersection/containment). If a row is contained it becomes selected.
    The remaining code in MousePressed is used if node(s) were previously selected it goes through and checks to see if this mouse press is at the location of one of the previous selected nodes - if it is then you can drag that node along with all of its siblings to their destination. However if your mouse press is not on one of the selected nodes - all the nodes should be deselected (like in explorer if you press away from your selection, you lose it). If you select and begin to drag your selection dontRelease should not allow the creation of another "selection" rectangle to occur during the drag-n-drop process.
    -That's how I thought this code should work. Unfortunately as it does most of these things it does not correctly implement rule #2 of Windows Explorer (2. only by dragging one of the selected nodes can you drag them, otherwise you lose them)...currently as long as something is selected you can do a mouse press and drag from another location and as long as that location does not contain a node (like it is a blank area in the JTree), you can drag everything to the destination from when you start dragging.
    I looked around and saw that perhaps it is due to the BasicTreeUI interferring with it's own MouseInputHandler() so I wrote MyTreeUI that extends BasicTreeUI, basically changing only the MouseInputHandler to contain the functions above, and I blocked /**/ those functions from my MyTree Constructor.
    Then in my main class (the one of instantiate my MyTree and my DefaultMutableTreeNodes), I wrote:
    try
    String myTreeUI = "MyTreeUI";
    UIManager.put( "MyTreeUI", myTreeUI );
    UIManager.put( myTreeUI,
    Class.forName( myTreeUI ) );
    } catch( ClassNotFoundException cnfe ) {
    System.err.println( "My Tree UI class not found" );
    System.err.println( cnfe );
    ...thinking that that would be all I needed in order to set MyTreeUI as the JTree's UI, LooknFeel, etc. and although I did not get that ClassNotFoundException when running the program, it did not have any of the functionality that I had written ( I even wrote a System.out.println() in my MousePressed() function in MyTreeUI so that it would let me know that it is working and it never appeared). It was as if the MyTreeUI was not loaded or attached to the JTree. I also called:
    System.out.println("this is UI: " + jTree1.getUIClassID() );
    to see which UI my MyTree instantiate was using and it would printout TreeUI, not MyTreeUI. So I'm wondering what it is I'm doing wrong, I think I am very close to having this thing working but I want to know if anybody here would be able to let me know what I'm doing wrong or what would be the best way to go about implementing this Windows Explorer Multiple Selection JTree.
    Sorry for the long-winded explanation,
    -Meddev24.

Maybe you are looking for

  • Flat File to IDOC Mapping requirement to generate Multiple Segments

    Hi Experts, I got a requirement were i have 2 records in a file and i need to generate 2 IDOCs  with  multiple segments in it. FILE : 10/01/2010     101  KRNA     ic_quantity          30-0257     3526     1     1     ea     110000     10 10/01/2010  

  • Non-genuine charger - dangerous?

    I bought a desktop cradle for my N95 8GB off of Ebay, and it works well. My only concern is that the charger it comes with is not a genuine Nokia product, and obviously I don't want to fry my battery. It charges normally, and when full the phone says

  • Html tags in color when in source

    Happy New Year to all! Why is it when looking at "Source" under properties, the tags appearing are in different colors? Where can I find more info about this? Thanks to all!

  • How to Transport VC Content from NetWeaver 7.0 to NetWeaver 7.4

    Hi I am following the wiki: http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/c084eeac-b97a-2c10-e8b0-a27b5608b5d2?overridelayout=true http://wiki.scn.sap.com/wiki/display/BOBJ/BI4+-+NW+Java+WAS+7.3+EP+and+BI4+portal+applications?ori

  • Adobe Reader + IE, caching fails

    Here is the problem: http://stackoverflow.com/questions/1807753/enable-pdf-caching-in-ie Before I renamed viewFile to viewFile.pdf, the caching didn't work anywhere with adobe reader. But it worked with https://addons.mozilla.org/en-US/firefox/addon/