Allowing for multiple selections in a JTree

Use TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION!

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      final JTree tree = new JTree(root);
 
      TreeSelectionModel model = new DefaultTreeSelectionModel();
      model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
      tree.setSelectionModel(model);
 
      JButton button = new JButton("Display selected values on stdout");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            TreePath[] treePaths = tree.getSelectionPaths();    
            for (int i=0; i<treePaths.length; i++) {
               System.out.println(treePaths[i].getLastPathComponent());    
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(tree));
      getContentPane().add(BorderLayout.SOUTH, button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}