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.swing;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
public class JTreeSelectionListenerDemo extends JFrame {
public JTreeSelectionListenerDemo() throws HeadlessException {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new JTreeSelectionListenerDemo().setVisible(true));
}
private void initializeUI() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.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(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();
});
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(200, 400));
getContentPane().add(pane);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024