JTree select item with right click

I know how to get the item from the selected item with the left mouse button. I can use TreeSelectionListener

.

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

      

But I need to get the item by right clicking. Show the popup menu that is associated with the item that was clicked. I've 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 the user clicks on the element with the right click its problem. Right clicking does not select an item. How to select an element by event coordinates or how to solve it? Primary I need to get an object that hasn't clicked on the select item, if possible.

+3


source to share


1 answer


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);

      

+8


source







All Articles