Set JTree to Single Tree Selection in Java
Description
The following code shows how to set JTree to Single Tree Selection.
Example
//www . j a v a 2 s .co m
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeSelectionModel;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("abcde");
DefaultMutableTreeNode node = new DefaultMutableTreeNode("1");
node.add(new DefaultMutableTreeNode("java2s.com"));
node.add(new DefaultMutableTreeNode("a"));
root.add(node);
root.add(new DefaultMutableTreeNode("b"));
TreeModel tm = new DefaultTreeModel(root);
JTree tree = new JTree(tm);
tree.getSelectionModel().addTreeSelectionListener(new Selector());
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
getContentPane().add(tree, BorderLayout.CENTER);
pack();
setVisible(true);
}
private class Selector implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent event) {
Object obj = event.getNewLeadSelectionPath().getLastPathComponent();
System.out.println("" + obj.toString().length());
}
}
public static void main(String[] args) {
Main m = new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »