Dynamically getting a Component by clicking on it

Hey is there a way to dynamically get a component by clicking on it?
So for example at runtime when I click on a component I can print out the some property of it in the console.
Thanks for the help

That is an interesting question. You can't simply use the root container's mouseClicked event because the click event will be consumed by the components when they are clicked on. Therefore, I imagine that you would have to add a listener to each component in the window to get this functionality.

A script like this would probably work for most components:

# Import MouseAdapter to create a click listener and BasicContainer for recursively finding nested components
from java.awt.event import MouseAdapter
from com.inductiveautomation.factorypmi.application.components import BasicContainer

# Define a class that extends MouseAdapter
class UbiquitousClickListener(MouseAdapter):
    
	# Override of the mouseClicked method in MouseAdapter
	def mouseClicked(self, event):
		# The component clicked on will always be event.source
		# Do whatever needs doing with the component on the mouse click event here	
		print event.source.name

# Sets mouse listeners on all components within a given container.
def setComponentListeners(container):
	# Iterating over each component within the provided container.
	for component in container.getComponents():
		# If another container is found, recursively call the setComponentListeners script
		if isinstance(component, BasicContainer):
			setComponentListeners(component)
		else:
			# Otherwise, add the click listener to the component
			component.addMouseListener(UbiquitousClickListener())
			
# Call the setComponentListeners function, passing in the root container
# Note: the way this is written, it will work from almost anywhere in the window, 
# ...but each time this script runs, it will add a redundant listener to each component
# ...so it should be ran from somewhere like the parent window's internalFrameOpened event hander where it can't run more than once.
# ...However, if this is needed for some designer utility purpose, it could be ran from a temporary button
# ...just don't click it multiple times
setComponentListeners(system.gui.getParentWindow(event).rootContainer)

It creates a custom listener that it applies to every component in the window that is in the root container or a nested container. If you need it to crawl through template repeaters or canvases, further development would be required.

2 Likes

Thank you thats a smart solution, I have never thought of modifying the methods themselves. That is a good thing to keep in mind.