Select multiple nodes in a JTree a right click

Hi all,
I've a JTree and I'd like to allow the user select some nodes (one or more) right click and than show a popupMenu.
This behavior seems not to be easy, because if I select a single node (right clicking on it) the node does not appear selected ; I need to select it left clicking and than everything works fine.
I read some posts found in the forum and the solution seems to be :
- attach a mouseListener to the JTree
- get the TreePath of the node selected
- force the selection on the node with setSelectionPath(TreePath)
This works fine if you need to select only one node, cause if you have to select more, you simply cannot.
I wonder a so obvious behavior is so hard to achieve.
I hope somebody out there had made the magic.
Any help would be appreciated.
Flavio Palumbo

Hi Darryl,
I wrote the test case below.
Using the methods you suggested it works almost fine.
The only behavior not desired is when you select a range (shift or control), release the key an than right click ; in this case remains selected the only node you clicked on ; to select the range clicking with the right button, you have to keep pressed the key.
Any hint would be appreciated.
Flavio
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
public class TestTree {
    JTree jtr = null;
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestTree();
    public TestTree() {
        JFrame jf = new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
            javax.swing.SwingUtilities.updateComponentTreeUI(jf);
        } catch (Throwable e) {
        jf.setPreferredSize(new java.awt.Dimension(200, 560));
        javax.swing.JScrollPane js = new javax.swing.JScrollPane();
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
        jtr = new JTree(root);
        jtr.addMouseListener(new TestTreeML());
        js.setViewportView(jtr);
        jf.getContentPane().add(js);
        for (int i = 0; i < 20; i++) {
            DefaultMutableTreeNode nodoFiglio = new DefaultMutableTreeNode("nodo" + i);
            ((DefaultTreeModel) jtr.getModel()).insertNodeInto(nodoFiglio, root, root.getChildCount());
        jf.pack();
        jf.setVisible(true);
    public class TestTreeML extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
        @Override
        public void mouseClicked(MouseEvent e) {
            try {
                if (!e.getSource().equals(jtr)) {
                    return;
                TreePath tpSel = jtr.getPathForLocation(e.getX(), e.getY());
                if (tpSel == null) {
                    return;
                int i = 0;
                final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tpSel.getLastPathComponent();
                TreePath[] tpExisting = null;
                if (e.isControlDown() || e.isShiftDown()) {
                    System.out.println("control/shift");
                    TreePath[] tpEx = jtr.getSelectionPaths();
                    tpExisting = java.util.Arrays.copyOfRange(tpEx, 0, tpEx.length + 1);
                    i = tpEx.length;
                } else {
                    tpExisting = new TreePath[1];
                tpExisting[i] = tpSel;
                jtr.setSelectionPaths(tpExisting);
                if (e.getClickCount() == 2) {
                    System.out.println("double click on " + node.getUserObject());
                if (javax.swing.SwingUtilities.isRightMouseButton(e)) {
                    if (!e.isControlDown()) {
                        jtr.setSelectionPath(tpSel);
                    JPopupMenu menu = new JPopupMenu();
                    JMenuItem it0 = new JMenuItem("Option1");
                    it0.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println("Option1 on " + node.getUserObject());
                    menu.add(it0);
                    JMenuItem it1 = new JMenuItem("Option2");
                    it1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println("Option2 on " + node.getUserObject());
                    menu.add(it1);
                    menu.show(jtr, e.getX(), e.getY());
            } catch (Throwable t) {
}

Similar Messages

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

  • Selecting multiple nodes of a tree through ctrl+shift

    Can i select multiple nodes of a tree through ctrl+shift.
    How??
    Thanx

    Take a look at JTree#getSelectionModel() and TreeSelectionModel#setSelectionMode(int).
    _myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

  • How to select a node in a JTree by name

    I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
    Thanks!

    I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
    So in short, I have the String name of the node that I want to programatically select.
    Thanks!

  • Selecting a node in a JTree knowing his path

    Hello for all,
    I'm trying to select a specific node in a JTree component by clicking a button.. this is my code :
    private DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("root");
    private DefaultTreeModel treeModel = new DefaultTreeModel(treeNode);
    private JTree tree = new JTree(treeModel);
    private JButton button = new JButton("Select");
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("child1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("child2");
    child1.add(new DefaultMutableTreeNode("child11"));
    treeNode.add(child1);
    treeNode.add(child2);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TreePath path = new TreePath(new Object[]{"root", "child1"});               
        tree.setExpandsSelectedPaths(true);
        tree.scrollPathToVisible(path);
    });as you can see, I want to select the node with the path "root/child1"..
    but I'm getting this exception : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.tree.TreeNode..
    any ideas ?

    You will want to read the second sentence in the TreePath comments section.
    Also, read the second sentence in the TreePath Method Detail section for the
    getLastPathComponent method.
    With these clues &#8212; try getting a TreePath from the tree you are working with.
    For example, you can try something like tree.getPathForRow(row) using the
    visible row index of "child1". Since the TreePath returned comes from the tree
    it will understand what to do with it. You can check the class name of the
    components that are returned in the TreePath to confirm this. And it will
    explain the exception you quoted.

  • We used to be able to sort by multiple columns/rows at once by right clicking on the header and choosing show more options-how do we do that in the new Numbers?

    We used to be able to sort by multiple columns/rows at once by right clicking on the header and choosing show more options-how do we do that in the new Numbers?  It doesn't appear anywhere.  Do I now have to sort massive tables by each column one at a time now?  Also there used to be an easier way to merge/unmerge cells without me having to go to the table menu each time.  Am I missing something?

    Multiple column sort is a missing feature in the new version.  Hopefully soon to return. You can do a multicolumn sort by sorting one at a time in reverse order of importance.
    For merging and unmerging cells, I select the cells and right click to bring up the contextual menu. Merge and unmerge are on the menu.  You could also create keyboard shortcuts for Merge Cells and Unmerge Cells in the Table menu.

  • Selectively editing nodes in a JTree

    I need to make certain nodes in a JTree editable, without making every node in the tree editable. How can I accomplish this?

    Is there some kind of method in a JTree or a DefaultMutableTreeNode that I can call to select the node's text and be able to change it?Hmm. And you did read the API for JTree looking for such methods before you posted here, didn't you?
    So tell us which methods you found to be likely candidates.
    db

  • Then 'm selecting 3 points after camera tracker  and right click them there is no SET GROUND PLANE in the list, can U help me?

    Then 'm selecting 3 points and right click them there is no SET GROUND PLANE in the list, can U help me?

    Quit farting around with the camera tracker.  You're not nearly ready to handle it.  Go here:
    Getting started with After Effects (CS4, CS5, CS5.5,  CS6, & CC)

  • Can't select multiple objects in Pages 10 with "command+click".

    I've always been able to "command+click" to select multiple objects in Pages. However, since I updated to Pages 10, this shortcut does not work. Any thoughts?

    Apple is trying to make the iOS version and Mac versions match. Some incredibly stupid or lazy developers/designers took the iOS version as the standard and changed the OSX version to match. The stupidity in this is that iOS is not a good platform for work in the first place, it's incredibly cludgy to edit/write documents on the ipad, email maybe but editing real documents is a pain is the wazoo. The iPad is ok for watching videos, reading, browsing, but not for efficient work. Being able to select multiple items and work on them is a basic feature of most editors and has been for years. Microsoft Office for OSX is so much better that it will be difficult for Apple can catch up even if they wanted to. It's too bad for Apple makes prettier apps. And now MS Word for the iPad is available and free.

  • Multiple entries "Open With" command after right clicking inline attachment

    In Mail, when I receive an attachment that's open inline in the email, I right click it, and choose "open with", I get a long list of programs to choose from. The problem is, most programs are listed many times. For example, I right click on a PDF, and select "open with" and Quicktime Player.app is listed seventeen times! So what ought to be a list that includes perhaps a dozen entries, is so long I have to scroll through it on a 30" monitor!
    How do I get each application to show up only once on this list?
    Thanks

    Are you using Time Machine to back up your entire boot drive, including your /Applications folder? It's possible that Spotlight is somehow putting all those entries in the Launch Services database.
    I'd recommend:
    1) Going to the Spotlight preferences and adding the Time Machine drive to the "exclude" list, and seeing whether that fixes the issue.
    2) If not, then leave the drive excluded, and try rebuilding the Launch Services database. Here's an article on Mac OS X Hints which shows how to do this on 10.5:
    http://www.macosxhints.com/article.php?story=20071102084155353
    The comment about deleting the launchservices.plist file is because this is definitely an issue with Launch Services (that's what determines what applications can open which files). But deleting the plist file may not be the right way to fix this issue.

  • How can I select multiple nodes by standard

    I want to ask how can I modify this example code to enable multiple selection, say if I select node1, system out display node1, then ctr+node2 selection. system out display node1&node2.
    The code below, only display node1, then when I do ctr+node2 selection, system out still display node1.
    I am quite new to JTree, so, please if there is anyone can give a solution?
    Thanks
    * A 1.4 application that requires the following additional files:
    *   TreeDemoHelp.html
    *    arnold.html
    *    bloch.html
    *    chan.html
    *    jls.html
    *    swingtutorial.html
    *    tutorial.html
    *    tutorialcont.html
    *    vm.html
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import java.net.URL;
    import java.io.IOException;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TreeDemo extends JPanel
                          implements TreeSelectionListener {
        private JEditorPane htmlPane;
        private JTree tree;
        private URL helpURL;
        private static boolean DEBUG = false;
        //Optionally play with line styles.  Possible values are
    //  "Angled" (the default), "Horizontal", and "None".
        private static boolean playWithLineStyle = false;
        private static String lineStyle = "Horizontal";
        //Optionally set the look and feel.
        private static boolean useSystemLookAndFeel = false;
        public TreeDemo() {
            super(new GridLayout(1,0));
            //Create the nodes.
            DefaultMutableTreeNode top =
                new DefaultMutableTreeNode("The Java Series");
            createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);---->Cause problem, when press Ctr to multiple select, always the first selected node is returned, which is shown in System out
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
            if (playWithLineStyle) {
                System.out.println("line style = " + lineStyle);
                tree.putClientProperty("JTree.lineStyle", lineStyle);
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
            //Create the HTML viewing pane.
            htmlPane = new JEditorPane();
            htmlPane.setEditable(false);
            initHelp();
            JScrollPane htmlView = new JScrollPane(htmlPane);
            //Add the scroll panes to a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
            splitPane.setTopComponent(treeView);
            splitPane.setBottomComponent(htmlView);
            Dimension minimumSize = new Dimension(100, 50);
            htmlView.setMinimumSize(minimumSize);
            treeView.setMinimumSize(minimumSize);
            splitPane.setDividerLocation(100); //XXX: ignored in some releases
                                               //of Swing. bug 4101306
            //workaround for bug 4101306:
            //treeView.setPreferredSize(new Dimension(100, 100));
            splitPane.setPreferredSize(new Dimension(500, 300));
            //Add the split pane to this panel.
            add(splitPane);
        /** Required by TreeSelectionListener interface. */
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                               tree.getLastSelectedPathComponent();
            if (node == null) return;
            Object nodeInfo = node.getUserObject();
            System.out.print("\nMy selection node is"+nodeInfo.toString());
            if (node.isLeaf()) {
                BookInfo book = (BookInfo)nodeInfo;
                displayURL(book.bookURL);
                if (DEBUG) {
                    System.out.print(book.bookURL + ":  \n    ");
            } else {
                displayURL(helpURL);
            if (DEBUG) {
                System.out.println(nodeInfo.toString());
        private class BookInfo {
            public String bookName;
            public URL bookURL;
            public BookInfo(String book, String filename) {
                bookName = book;
                bookURL = TreeDemo.class.getResource(filename);
                if (bookURL == null) {
                    System.err.println("Couldn't find file: "
                                       + filename);
            public String toString() {
                return bookName;
        private void initHelp() {
            String s = "TreeDemoHelp.html";
            helpURL = TreeDemo.class.getResource(s);
            if (helpURL == null) {
                System.err.println("Couldn't open help file: " + s);
            } else if (DEBUG) {
                System.out.println("Help URL is " + helpURL);
            displayURL(helpURL);
        private void displayURL(URL url) {
            try {
                if (url != null) {
                    htmlPane.setPage(url);
                } else { //null url
              htmlPane.setText("File Not Found");
                    if (DEBUG) {
                        System.out.println("Attempted to display a null URL.");
            } catch (IOException e) {
                System.err.println("Attempted to read a bad URL: " + url);
        private void createNodes(DefaultMutableTreeNode top) {
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode book = null;
            category = new DefaultMutableTreeNode("Books for Java Programmers");
            top.add(category);
            //original Tutorial
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Tutorial: A Short Course on the Basics",
                "tutorial.html"));
            category.add(book);
            //Tutorial Continued
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Tutorial Continued: The Rest of the JDK",
                "tutorialcont.html"));
            category.add(book);
            //JFC Swing Tutorial
            book = new DefaultMutableTreeNode(new BookInfo
                ("The JFC Swing Tutorial: A Guide to Constructing GUIs",
                "swingtutorial.html"));
            category.add(book);
            //Bloch
            book = new DefaultMutableTreeNode(new BookInfo
                ("Effective Java Programming Language Guide",
              "bloch.html"));
            category.add(book);
            //Arnold/Gosling
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Programming Language", "arnold.html"));
            category.add(book);
            //Chan
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Developers Almanac",
                 "chan.html"));
            category.add(book);
            category = new DefaultMutableTreeNode("Books for Java Implementers");
            top.add(category);
            //VM
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Virtual Machine Specification",
                 "vm.html"));
            category.add(book);
            //Language Spec
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Language Specification",
                 "jls.html"));
            category.add(book);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            if (useSystemLookAndFeel) {
                try {
                    UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    System.err.println("Couldn't use system look and feel.");
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TreeDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TreeDemo newContentPane = new TreeDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    you can use the method getSelectionPaths() in the class JTree. It will return an array of all the TreePaths you have selected. Then on each of the TreePath you got use the method getLastPathComponent() to get the nodes which you have selected.
    Hope this solves your problem.

  • How to select multiple nodes, which are not next to each other,  in a tree?

    The following code suppose to allow user select any combination of nodes (because of DISCONTIGUOUS_TREE_SELECTION), however, I can only select nodes which are next to each other. Can some one told me how to make this DISCONTIGUOUS_TREE_SELECTION work?
    Thank you very much!
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TestTree extends JFrame {
    public TestTree() {
    super();
    setBounds(0,0,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTree tree = new JTree();
    getContentPane().add(tree);
    TreeSelectionModel model = new DefaultTreeSelectionModel();
    model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setSelectionModel(model);
    public static void main(String [] args) {
    TestTree test = new TestTree();
    test.show();

    In Windows you hold down the Ctrl key while clicking on the nodes you want to select. Don't know the equivalent in other environments.

  • Right click select node in tree (for a standalone Air app)?

    For the sake of userfriendliness (in regard to a context menu) I wold like to "move" the selected node in a tree to the node that currently has the focus when right clicking it - like how the context menu access in windows file explorer works (focus and selected item are always the same  when right clicking).
    In worst case scenario I would like to disable a created context menu if the selected node and the node that currently has the focus are not the same).
    Now users can get confused when right clicking to access my context menu, in the tree structure, if the selected node and the node they are currently hovering over (and thus are in focus) are different.
    I was thinking of finding which node currently has the focus and then making that node the selected node - but I cant get it to work:-).
    Please, help a beginner.

    Hi,
    Duplicate thread of
    http://swforum.sun.com/jive/thread.jspa?threadID=64518
    MJ

  • How to get a pop-up menu on right click of JTree?

    hi
    My application consists of a JTree.I am having a 2 root nodes each one have some child nodes.in the first root node what i want is on right click of child node i have to display one option that is enabled and on the second root node what i want is on right click of child node i have to display one option that is disabled..
    how to do that
    thanks for your reply in advance,

    When you are creating your nodes, do node.setUserObject(objectName);
    and on right click, do something like this
    if (e.isPopupTrigger() == true) {
             selPath = tree.getPathForLocation(e.getX(), e.getY());
          try {
             // If Right Click, Select the Node
             Object[] selectedPath = selPath.getPath();
             DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath[selectedPath.length - 1];
             try {
                dataObject = (MyObject) selectedNode.getUserObject(); // Set the Data Object
             } catch (ClassCastException ex) {
                                      ex.printStackTrace();
             // Check for the right click on Framework Node
             if (dataObject.getClass().isInstance(new MyObject()) == true) {
                // Disable the pop-up menu
    ....

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

Maybe you are looking for