The following example show how to use the JTree.getSelectionPaths()
method to get the selected node of a JTree
component. This method returns an array of TreePath
objects. In the case to get the last node in the path we can call the TreePath.getLastPathComponent()
.
In the code below when you pressed the button the listener gets the selection paths and print out the last path component of the selected nodes.
package org.kodejava.swing;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
public class JTreeGetSelectedNode extends JFrame {
public JTreeGetSelectedNode() throws HeadlessException {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new JTreeGetSelectedNode().setVisible(true));
}
private void initializeUI() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Countries");
DefaultMutableTreeNode asia = new DefaultMutableTreeNode("Asia");
String[] countries = new String[]{"India", "Singapore", "Indonesia", "Vietnam"};
for (String country : countries) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
asia.add(node);
}
DefaultMutableTreeNode northAmerica = new DefaultMutableTreeNode("North America");
countries = new String[]{"United States", "Canada"};
for (String country : countries) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
northAmerica.add(node);
}
DefaultMutableTreeNode southAmerica = new DefaultMutableTreeNode("South America");
countries = new String[]{"Brazil", "Argetina", "Uruguay"};
for (String country : countries) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
southAmerica.add(node);
}
DefaultMutableTreeNode europe = new DefaultMutableTreeNode("Europe");
countries = new String[]{"United Kingdom", "Germany", "Spain", "France", "Italy"};
for (String country : countries) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
europe.add(node);
}
root.add(asia);
root.add(northAmerica);
root.add(southAmerica);
root.add(europe);
final JTree tree = new JTree(root);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(500, 500));
JButton button = new JButton("Get Selected");
button.addActionListener(e -> {
TreePath[] paths = tree.getSelectionPaths();
for (TreePath path : paths != null ? paths : new TreePath[0]) {
System.out.println("You've selected: " + path.getLastPathComponent());
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(pane, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.SOUTH);
}
}
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