I am trying to write a program that "associates" a node in JTree with
data. If you take for example an Employee which would be a node in a
jtree. What would i need to do to get data(name, ssn,etc..)
associated with the employee to dispaly once the node was clicked
on.
Thanks.
p.s. I have already figured out how to contruct and add items a jtree.
I read this and thought "I've never used a JTree before, I wonder how
hard that might be"
....
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class TreeTest extends JPanel {
JTree tree;
TreeTest() {
Person ceo = new Person("Steve Gates", "123-456-789");
DefaultMutableTreeNode root = new DefaultMutableTreeNode(ceo);
Person fd = new Person("Bill Jobs", "013-453-263");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode(fd);
root.add(child1);
Person hrd = new Person("Darl Torvalds", "987-765-324");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode(hrd);
root.add(child2);
final JTree tree = new JTree(root);
add(new JScrollPane(tree));
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(
e.getX(), e.getY());
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)
selPath.getLastPathComponent();
Person x = (Person)node.getUserObject();
if (selRow != -1) {
if (e.getClickCount() == 2) {
JOptionPane.showMessageDialog(
null, x.allAboutMe());
}
}
}
};
tree.addMouseListener(ml);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Tree Test");
f.add(new TreeTest());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
});
}
}
class Person {
String name;
String ssn;
Person(String name, String ssn) {
this.name = name;
this.ssn = ssn;
}
public String allAboutMe() {
return "Name: " + name + ", SSN: " + ssn;
}
public String toString() {
return name;
}
}
Doubtless the above can be improved enormously. I just quickly cut &
pasted the examples in the Javadocs and looked for suitable methods to
get objects out. If I was to use a JTree for real I'd try to use
generics to get rid of the type casts and maybe look for other types of
listeners that could be used (node selected?)