Listbox Foreground or Background Dynamic Color change via Python

I did something like this once with a dropdown component. I imagine that the list component works the same way. Your button script will have to override the renderer, and allow you to insert you own colors.

Here is an example that would work in the context you've defined:

from com.inductiveautomation.plaf import ComboListCellRenderer

# Override the cell renderer for custom functionality
class ColorCellRenderer(ComboListCellRenderer):
	def getListCellRendererComponent(self, list, value, index, isSelected, cellHasFocus):
		ComboListCellRenderer.getListCellRendererComponent(self, list, value, index, isSelected, cellHasFocus)
		
		# Normally the first if condition would be a cellHasFocus condition to indicate the presence of the mouse,
		# ...but it doesn't have an effect on the list component,
		# ...so additional development would be needed to add this functionality
		
		# Give the selected item a destinct color
		if isSelected:
			self.foreground = system.gui.color('black')
			self.background = system.gui.color('white')
		
		# Color the foreground and background of the individual indexes according to the foreground and background color lists
		else:
			self.foreground = system.gui.color(foregroundColors[index])
			self.background = system.gui.color(backgroundColors[index])
		
		return self

# Define a list of colors that corresponds with the indexes in the JList.
foregroundColors = ['red', 'orange', 'yellow', 'lightgreen', 'green', 'lightblue', 'purple', 'grey', 'brown']
backgroundColors = ['brown', 'red', 'orange', 'yellow', 'lightgreen', 'green', 'lightblue', 'purple', 'grey']

# Create an instance of the custom renderer
renderer = ColorCellRenderer()

# Get the JList [view] from the listbox's viewport and set the custom renderer
event.source.parent.getComponent('List').viewport.view.setCellRenderer(renderer)

Result:
image

Edit: Refactored ColorCellRender per the feedback below

2 Likes