Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTree select item on right click

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.

like image 998
SpeedEX505 Avatar asked Dec 14 '14 10:12

SpeedEX505


1 Answers

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);
like image 89
Mailkov Avatar answered Oct 27 '22 00:10

Mailkov