How do I add selection listener to JTree?
Category: javax.swing, viewed: 94 time(s).
This example shows you how to use the TreeSelectionListener to add a tree selection listener to the JTree component. In the listener method below you can see how to get the selected path and print out the selected path to the console.
package org.kodejava.example.swing;
import javax.swing.*;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
public class JTreeSelectionListenerDemo extends JFrame {
public JTreeSelectionListenerDemo() throws HeadlessException {
initializeUI();
}
private void initializeUI() {
setSize(200, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode chapterOne = new DefaultMutableTreeNode("Chapter One");
DefaultMutableTreeNode one = new DefaultMutableTreeNode("1.1");
DefaultMutableTreeNode two = new DefaultMutableTreeNode("1.2");
DefaultMutableTreeNode three = new DefaultMutableTreeNode("1.3");
root.add(chapterOne);
chapterOne.add(one);
chapterOne.add(two);
chapterOne.add(three);
JTree tree = new JTree(root);
tree.addTreeSelectionListener(createSelectionListener());
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(200, 400));
getContentPane().add(pane);
}
private TreeSelectionListener createSelectionListener() {
return new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getPath();
int pathCount = path.getPathCount();
for (int i = 0; i < pathCount; i++) {
System.out.print(path.getPathComponent(i).toString());
if (i + 1 != pathCount) {
System.out.print("|");
}
}
System.out.println("");
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JTreeSelectionListenerDemo().setVisible(true);
}
});
}
}
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!