Search code examples
javajfreechart

Setting series visiblity to False also hides it from the legend


I am using JFreeChart.

When i click on a Legend item i have put a listener. In the listener i make the series that was clicked invisble. But as a side effect the series also vanishes from the Legend.

I do not want the series to vanish from the legend. What can i do so that i can show/hide series on the plot but not affect the legend.

Setting the Legend to be fixed using plot.setFixedLegendItems(list) cause other mouse effects to stop working (on mouse over of data point the series line currently becomes thicker and the same in the legend).

chartPanel.addChartMouseListener(new ChartMouseListener() {
    @Override
    public void chartMouseClicked(ChartMouseEvent event) {
        ChartEntity entity = event.getEntity();
        if (entity instanceof LegendItemEntity) {
            //*
            LegendItemEntity itemEntity = (LegendItemEntity) entity;
            XYDataset dataset = (XYDataset) itemEntity.getDataset();
            int index = dataset.indexOf(itemEntity.getSeriesKey());
            XYPlot plot = (XYPlot) event.getChart().getPlot();

            //set the renderer to hide the series
            XYItemRenderer renderer = plot.getRenderer();
            renderer.setSeriesVisible(index, !renderer.isSeriesVisible(index), false);
            renderer.setSeriesVisibleInLegend(index, true, false);
            //*/        
        }
    }
});

Solution

  • It is the getLegendItems() method in the XYPlot class that does the visibility checking, so you could subclass XYPlot and override this method (or modify it directly if you want to build your own custom version of JFreeChart).