JTree select item on right click
Asked Answered
I

1

7

I know how to get item from selected item my left mouse button click. I can use TreeSelectionListener.

tree.addTreeSelectionListener(new TreeSelectionListener(){
    @Override
    public void valueChanged(TreeSelectionEvent tse) {
        DefaultMutableTreeNode node = 
                (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    }
});

But I need to get item clicked by right mouse button. Show popup menu which is related to item which was clicked. I tried this:

private void treeClicked(java.awt.event.MouseEvent evt) {
    if(SwingUtilities.isRightMouseButton(evt)){
        this.listRightClickMenu.show(this,evt.getX(),evt.getY());
            DefaultMutableTreeNode node = 
        (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    }
}                            

But if user click on item with right button its problem. Right click doesn't select item. How to select item by event coords or how to solve this? Primary I need to get object which is clicked no select item if its possible.

Iota answered 14/12, 2014 at 10:20 Comment(0)
E
14

Use this MouseListener:

MouseListener ml = new MouseAdapter() {
     public void mousePressed(MouseEvent e) {
         if(SwingUtilities.isRightMouseButton(e)){
         int selRow = tree.getRowForLocation(e.getX(), e.getY());
         TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
                 tree.setSelectionPath(selPath); 
                 if (selRow>-1){
                    tree.setSelectionRow(selRow); 
                 }
     }
 };
 tree.addMouseListener(ml);
Edgington answered 14/12, 2014 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.