Reputation: 697
I know I can add a mouseListener to a Jtree, but I need to double click on one of his elements and doSomething();
Upvotes: 1
Views: 2358
Reputation: 16403
From the documentation of JTree:
If you are interested in detecting either double-click events or when a user clicks on a node, regardless of whether or not it was selected, we recommend you do the following:
final JTree 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());
if(selRow != -1) {
if(e.getClickCount() == 1) {
mySingleClick(selRow, selPath);
}
else if(e.getClickCount() == 2) {
myDoubleClick(selRow, selPath);
}
}
}
};
tree.addMouseListener(ml);
Upvotes: 5
Reputation: 172398
Check this:-
public class NetworkTree extends JPanel implements TreeSelectionListener {
private JTree tree;
private static int PANEL_WIDTH=250;
private static int PANEL_HEIGHT=500;
private static String lineStyle = "Horizontal";
public NetworkTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode(new Site(
1,1,"Network","",3));
getSubNodes(top,0);
tree = new JTree(top);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(this);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
newNodeSelected();
}
});
}
.....
public void newNodeSelected() {
JOptionPane.showMessageDialog(null,"Hello");
}
..... }
Upvotes: 1