JTree: getPathForLocation(int x, int y)
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class MainClass extends JPanel {
public MainClass() {
final JTree tree;
final JTextField jtf;
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
tree = new JTree(top);
JScrollPane jsp = new JScrollPane(tree);
add(jsp, BorderLayout.CENTER);
jtf = new JTextField("", 20);
add(jtf, BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if (tp != null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
Related examples in the same category
1. | Tree.closedIcon | | |
2. | Tree.collapsedIcon | | |
3. | Tree.expandedIcon | | |
4. | Tree.leafIcon | | |
5. | Tree.openIcon | | |
6. | JTree.DynamicUtilTreeNode: createChildren(DefaultMutableTreeNode parent, Object children) | | |
7. | new JTree() | | |
8. | new JTree(TreeNode root) | | |
9. | new JTree(Vector vector) | | |
10. | JTree: addTreeSelectionListener(TreeSelectionListener tsl) | | |
11. | JTree: addTreeWillExpandListener(TreeWillExpandListener tel) | | |
12. | JTree: convertValueToText(Object v,boolean s,boolean e,boolean l,int r,boolean h) | | |
13. | JTree: getCellRenderer() | | |
14. | JTree: getLeadSelectionRow() | | |
15. | JTree: getMaxSelectionRow() | | |
16. | JTree: getMinSelectionRow() | | |
17. | JTree: getNextMatch(String prefix, int startingRow, Bias bias) | | |
18. | JTree: getRowHeight() | | |
19. | JTree: getSelectionRows() | | |
20. | JTree: putClientProperty('JTree.lineStyle', 'None') | | |
21. | JTree: setAutoscrolls(boolean b) | | |
22. | JTree: setCellEditor(TreeCellEditor editor) | | |
23. | JTree: setExpandedState(TreePath path, boolean state) | | |
24. | JTree: setRowHeight(int rowHeight) | | |
25. | JTree: setTransferHandler(TransferHandler newHandler) (Drag and drop files from file explore) | | |