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);

Similar Messages

  • What's happening on my iMac?  There are two choices of selected start up disks appearance without hold down option key.  On the other hand, it start up normally show apple picture when I hold option key.

    There are two choices of selected start up disks:Main HD and Recovery HD, appearance without hold down option key.  On the other hand, it start up normally show apple picture when I hold option key.

    Hi artdiva28
    Welcome to Apple Discussions
    First go to *System Preferences > Startup Disk* > select the *Mac OS X 10.5. on Macintosh HD* > click the Lock > hit the Restart button.
    Then if the iMac is still having trouble starting up, insert your Install Disk and restart holding the Option key. In Startup Manager select the Install Disk and boot into it, choose your language, skip the Installer and go up on the menu bar to Utilities and open Disk Utility. In Disk Utility select your Macintosh HD and hit the Repair button. Once finished note any errors and what was repaired for future reference. Quit Disk Utility and restart once again holding the Option key boot back into the Macintosh HD and eject the Install Disk.
    Also see > http://support.apple.com/kb/HT2956
    Dennis

  • I have itunes directory on an external hard drive and want to direct a new installation of itunes on windows 8 to use it. I tried holding down ctrl and clicking itunes and after many tries got it to work one time. When I went back in later it had reverted

    I have itunes directory on an external hard drive and want to direct a new installation of itunes on windows 8 to use it. I tried holding down ctrl and clicking itunes and after many tries got it to work one time. When I went back in later it had reverted back to a blank version of itunes and I cant get ctrl to work again. Any other ideas?

    This is sometimes caused by a problem with the iTunesPrefs.xml file, normally found at C:\Users\<User>\AppData\Local\Apple Computer\iTunes\iTunesPrefs.xml. Try dragging this to the desktop and trying again.
    Alternatively the problem may be that you have McAfee AV and it is preventing iTunes from updating the same file and thus causing the problem. See Why does iTunes delete my itunesprefs.xml? for details.
    tt2

  • I'd like to know how can u put letters on caps without holding all times the shift key?

    I'd like to know how can u put letters on caps without holding all times the shift key?

    Settings>General>Keyboard>Enable Caps Lock>On. Then just tap the shift key quickly.

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

  • When I click on a web link and hold down ctrl the page will not open into a new tab, it is just opening in a new window. How do I correct this?

    When I use to hold down the ctrl key and left click on a web link, the page use to open into a new tab. For some reason this is not working anymore. Instead when I hold down the ctrl key and left click on a web link, the link will open into a new window. How do I fix this?

    I figured out how to correct it. Not sure what exactly was happening. But I started into private browsing and then turned it off. It's been working correctly ever since I did private browsing.

  • Multiple select options in 1 drop down box?

    Hi,
    I have created a form that works perfectly except for the fact that I need to provide multiple select options in the 1 drop down box; for example, I'm asking what product the customer is interested in and his answer could be multiple items such as Soap, Sanitizer, Hand Towels, Face Cloths etc...
    At the moment, the customer can only select 1 item not multiple.
    Is this possible?
    Thanks in advance for the help!

    Hi,
    It is not possible to allow the user to select multiple items in a dropdown list.
    You could use a list box, which does allow multiple selections.
    Good luck,
    Niall
    Assure Dynamics

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

  • I am dual booting my mackbook pro with windows 7 64 bit. Yesterday it started locking up at the disk drive selections screen, when you hold down the "option" butting when powering on. I have been searching all morning, and so far nothing. Thanks. :)

    Hey folks,
    I have been using bootcamp for months now with windows 7 64 bit, and its been fine, yesterday while I was rebooting to do some gaming, at the hard drive selection screen when you boot holding the "options" butting down, it locks up when I select the windows drive and just sits there for ever. It doesn't throw an error, it boots fine into Lion.
    I searched all morning and didn't find anything, was hoping that someone might have an idea.
    Thanks in advance

    Search again. Microsoft has tips on what to do and Windows has a number of features
    system restore points
    automatic system repair using the Win7 DVD
    system restore image creation
    Just like you would with OS X Lion and Lion Recovery and Repair
    Use WinClone 3 www.twocanoes.com $20 to make an image just like you would with Disk Utility Restore or Carbon Copy Cloner
    rollback to last known good boot check point
    rollback a driver or program or any changes
    clean out temp files
    clean registry
    chkdsk
    https://discussions.apple.com/people/The%20hatter?view=bookmarks

  • I can't open a new tab using Ctrl+T or by clicking on the + symbol. I can, however, open a new tab when holding down Ctrl and clicking on a link. How can I fix this please?

    I used to be able to open a new tab using Ctrl+T but that has stopped working. Having I accidentally changed something?

    Disable the Ask Toolbar.

  • Multiple selection in JTree. Some Help!

    hi again! i have a doubt. how can i avoid to select two nodes, if they haven't got the same parent?i want not to select the second item if it has not got the same parent than the first selected one.
    is there anyone who can help me? thanks in advance...

    MathiasVersichele, welcome to the forum. Please don't post in threads that are long dead. When you have a question, start your own topic. Feel free to provide a link to an old post that may be relevant to your problem.
    I'm locking this thread now.
    db

  • I keep getting the error message "could not open a scratch file because the file is locked" even after resetting my preferences. I have to use Ctrl, Alt, Shift to start photoshop every time

    I'm unable to start Photoshop without holding down Ctrl, Alt, Shift each time I open it. Also Lightroom is now unable to open photos in Photoshop. I'm at a loss as to how to fix this.

    Hi there! Because the forum you originally posted in is for beginners trying to learn the basics of Photoshop, I moved your question to the Photoshop General Discussion forum, where you'll get more specialized help.
    To help others help you, please read through this article and provide any additional relevant details.

  • Cannot open links in new tab without holding Ctrl

    There is only one option i see in preferences for opening sites in new tabs. and it is called "Open links from applications..."
    Even with this checked, by default all links open in a new window, unless I hold down Ctrl while clicking the link.
    There MUST be a way to set ALL links to open in a new tab like every other browser I've used. No??

    Every single time this topic is raised, someone tries to claim there is a work-around, while seemingly forgetting that this is the Safari for Windows forum, and not the Safari for Mac forum.
    This is the single biggest glaring omission from Safari for Windows. It completely defeats the purpose of even having tabs, which makes me wonder what in the world were the developers thinking.
    Safari is a very pretty and fast browser, but I don't know many people who actually use it on a Windows machine due to the inability to simply open links in a new tab without right clicking or holding some extra button down. It's also the only mainstream browser for Windows that isn't capable of this simple task.
    Having watched this issue since Safari 3, without ever seeing any response other then "oh, but just do this work-around" (that only works for Macs), my guess is we'll never see it happen. The funny thing is that when you look at the ini files that can be changed on the Mac version, they are pretty much identical to the Windows version. So, the "fix" not working simply means that whoever was in charge of the part of code related to tabs when porting to Windows must have consciously decided there was no need for the ability to open links in new tabs.
    Proving once again that software engineers can be utterly clueless about the usability of their software.

  • Open window or tab to a link  without having to hold down a button

    Is it possible to not have have to keep holding down command or option in order to open a new window or tab. Make it so it opens in a a new window or tab automatically when you click instead of dissolving the current page and loading the link.
    Thanks !

    You can do two things, but they won't necessarily eliminate the need to hold down the command kay, and will sometimes have no effect at all, depending on the link.
    First, launch Terminal and copy/paste this command:
    defaults write com.apple.Safari TargetedClicksCreateTabs -bool true
    press Enter or Return, then quit Terminal. This will cause targeted links to open in a new tab automatically, without holding down the Command key. However, any links that have no target or are controlled by JavaScript will be unaffected and will open in the same window or tab.
    And, you can also download and install Glims, which offers even more features, and it's free.

Maybe you are looking for