I\'m trying to implement pop-up menus in Java JTree. I\'ve sub-classed DefaultTreeCellRenderer (to change node appearance) and DefaultTreeCellEditor (to create Components to
Call addRightClickListener()
to add the right-click context menu listener to your JTree
. Both overrides are for proper cross-platform functionality (Windows
and Linux
differ here).
private void addRightClickListener()
{
MouseListener mouseListener = new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent mouseEvent)
{
handleContextMenu(mouseEvent);
}
@Override
public void mouseReleased(MouseEvent mouseEvent)
{
handleContextMenu(mouseEvent);
}
};
tree.addMouseListener(mouseListener);
}
private void handleContextMenu(MouseEvent mouseEvent)
{
if (mouseEvent.isPopupTrigger())
{
MyContextMenu contextMenu = new MyContextMenu();
contextMenu.show(mouseEvent.getComponent(),
mouseEvent.getX(),
mouseEvent.getY());
}
}