I created a JTree and also created a class which implements TreeSelectionListener
then I pass that object into the JTree's function addTreeSelectionListener
.
In the JavaDocs, there is an example where they implemented the function public void valueChanged(TreeSelectionEvent e)
within the main class and passed this
into addTreeSelectionListener
. I tried to implement this into my class, but it didn't work.
package tutorials;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
public class TreeDemo extends JFrame{
private JTree tree;
public TreeDemo() {
super("Tree Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500, 300));
DefaultMutableTreeNode structure = new DefaultMutableTreeNode("Main Tree");
DefaultMutableTreeNode subTree1 = new DefaultMutableTreeNode("SubTree 1");
DefaultMutableTreeNode subTree2 = new DefaultMutableTreeNode("SubTree 2");
DefaultMutableTreeNode subTree3 = new DefaultMutableTreeNode("SubTree 3");
subTree1.add(new DefaultMutableTreeNode("SubSubTree"));
subTree1.add(new DefaultMutableTreeNode("SubSubTree2"));
subTree1.add(new DefaultMutableTreeNode("SubSubTree3"));
subTree1.add(new DefaultMutableTreeNode("SubSubTree4"));
structure.add(subTree1);
structure.add(subTree2);
structure.add(subTree3);
tree = new JTree(structure);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new treeListnerHandler());
pack();
add(tree);
}
private class treeListnerHandler implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent event) {
JOptionPane.showMessageDialog(null, event.getPath().getLastPathComponent().toString());
}
}
public static void main(String[] args) {
TreeDemo x = new TreeDemo();
x.setVisible(true);
}
}