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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With