Tree item context menu

I want to create a context menu based on where the user right-clicks on the tree view component.
How can I tell what element (if any) the user is right clicking on?

The only way is through the selected item or selected path properties of the tree view. If the selected item is -1 nothing is selected. The only problem is when the user right clicks on a different item than the one that is selected. There is no way of detecting that situation right now.

no hidden java class functions/properties I can reference?

Ok, ok. Here you go:if event.button == event.BUTTON3: tree = event.source.getViewport().getView() row = tree.getRowForLocation(event.x, event.y) path = tree.getPathForLocation(event.x, event.y) pathStr = "" if path != None: for item in path.getPath(): pathStr += str(item) + event.source.separationCharacter pathStr = pathStr[1:-1] event.source.setSelectedPath(pathStr) print event.source.selectedPath print event.source.selectedItem

1 Like

:prayer:

U da man Travis
:prayer:

I used Travis’s code, but I found it messes up if the view has been scrolled. Here’s a tweak that uses SwingUtilities to convert the click coordinates to compensate for scrolling in the Tree View.

if event.button == event.BUTTON3:	
	from javax.swing import SwingUtilities
	
	treeViewport = event.source.getViewport()
	treeView = treeViewport.getView()
	viewClick = SwingUtilities.convertPoint(treeViewport, event.x, event.y, treeView)

	row = treeView.getRowForLocation(viewClick.x, viewClick.y)
	path = treeView.getPathForLocation(viewClick.x, viewClick.y)
	pathStr = ""
	if path != None:
		for item in path.getPath():
			pathStr += str(item) + event.source.separationCharacter
		pathStr = pathStr[1:-1]

	event.source.setSelectedPath(pathStr)
	print event.source.selectedPath
	print event.source.selectedItem
2 Likes