Jfree chart - click on rendered data point

Yeah.

One way to do it is to create an annotation, it would be a little simpler if you were using an XYPlot as you could just use a XYShapeAnnotation, however, since you're using a bar chart that is a CategoryPlot so you need to create a custom annotation. Still not extremely complicated but not exactly straightforward either.

Add the following to you're configureChart extension function

from org.jfree.chart import ChartMouseListener
from org.jfree.chart.annotations import CategoryAnnotation
from java.awt import Color, BasicStroke

class CategoryShapeAnnotation(CategoryAnnotation):
	def __init__(self,newShape):
		self.shape = newShape

	def draw(self,g2,plot,dataArea,domainAxis,rangeAxis):
		#set the color that you want to highlight the item with
		#g2.setColor(Color.YELLOW) #to use a preset color constant
		g2.setColor(Color(1.0,1.0,0.0,1.0)) #to use a custom color with alpha
		#set the size of the stroke.
		g2.setStroke(BasicStroke(4.0))
		g2.draw(self.shape)
		
class CustomChartMouseListener(ChartMouseListener):
	def chartMouseMoved(self,e):
		pass
	def chartMouseClicked(self,e):
	    #verify that an entity was clicked on
		if e.getEntity():
			plot = e.getChart().getPlot()
			entityBounds = e.getEntity().getArea().getBounds2D()
			for a in plot.getAnnotations():
				#there should only ever be 1 annotation
				a.shape = entityBounds
				break
			else:
			    #if the annotation does not exist yet create it
				plot.addAnnotation(CategoryShapeAnnotation(e.getEntity().getArea().getBounds2D()))

for listener in self.getListeners(ChartMouseListener):
	self.removeChartMouseListener(listener)
	
self.addChartMouseListener(CustomChartMouseListener())

This will work for any categoryPlot.

3 Likes