Listening for Selection Events in a JTree Component : JTree Selection « Swing « Java Tutorial






import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;

public class Main {
  public static void main(String[] argv) throws Exception {

    JTree tree = new JTree();

    tree.addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent evt) {
        TreePath[] paths = evt.getPaths();

        for (int i = 0; i < paths.length; i++) {
          if (evt.isAddedPath(i)) {
            System.out.println("This node has been selected");
          } else {
            System.out.println("This node has been deselected"); 
          }
        }
      }
    });
  }
}








14.71.JTree Selection
14.71.1.Enabling and Disabling Multiple Selections in a JTree Component
14.71.2.Allow only a single node to be selected (default)Allow only a single node to be selected (default)
14.71.3.Allow selection to span one vertical contiguous set of visible nodes
14.71.4.Allow multiple selections of visible nodes
14.71.5.Listening for Selection Events in a JTree Component
14.71.6.Getting the Selected Nodes in a JTree Component
14.71.7.Returns a TreePath containing the specified node.
14.71.8.Determine if the third item is selected