Customize legend items on click i.e. for highlighting

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
d_koenig
Posts: 3
Joined: Sat Jan 17, 2009 8:01 pm

Customize legend items on click i.e. for highlighting

Post by d_koenig » Sat Jan 17, 2009 8:22 pm

Hello!

This is my first question here. I searched this board to find an answer if it is possible to make legend items clickable. I am sorry to repeat this question in case it is already answered because I did not find an answer.

I already know that a ChartPanel can add a MouseListener object, but I have two problems:
1) How to mark the selected legend item. For instance, how to set a border?
2) The item's label is not withing the Rectangle of the block. It only works by clicking next to the label on left side.

Code: Select all

final ChartPanel legendPanel = new ChartPanel(legendChart);
legendPanel.addMouseListener(new MouseListener(){
					@Override
					public void mouseClicked(MouseEvent e) {
					
						Point p = e.getPoint();
						List<Block> blockList =legendPanel.getChart().getLegend(0).getItemContainer().getBlocks();
						
						int blockCount = blockList.size();
						for(int i = 0; i < blockCount; i++){
							Block block = blockList.get(i);
							if(block.getBounds().contains(p)){
								System.out.println("Mouse clicked on block " + i); // now it's time to highlight the clicked item and to select the correct settings tab
								break;
							}
						}
					}
					@Override
					public void mouseEntered(MouseEvent e) {}
					@Override
					public void mouseExited(MouseEvent e) {}
					@Override
					public void mousePressed(MouseEvent e){}
					@Override
					public void mouseReleased(MouseEvent e) {}
		        });

Gotcha
Posts: 7
Joined: Wed Oct 15, 2008 9:13 am

Post by Gotcha » Thu Jan 22, 2009 3:30 pm

You must implement ChartMouseListener. Setup LegendItemEntity in chartMouseMoved like this ...

Code: Select all

	public void chartMouseMoved(ChartMouseEvent event) {
		// Hovering over the title legend?
		LegendItemEntity legendItemEntity = null;
		if (event.getEntity() instanceof LegendItemEntity) {
			legendItemEntity = (LegendItemEntity) event.getEntity();
		}

		if (hoveringOverLegendItemEntity != legendItemEntity) {
			hoveringOverLegendItemEntity = legendItemEntity;
			forceRedraw();
		}
	}
... then draw it (the function is from the ChartComposite, use this or the one from the ChartPanel) ...

Code: Select all

public void paintControl(PaintEvent e) {
...
		// Hovering over legend title item.
		if (hoveringOverLegendItemEntity != null) {
			e.gc.drawRectangle(SWTUtils.toSwtRectangle(hoveringOverLegendItemEntity.getArea().getBounds()));
		}
}

Locked