我有代码在点击LegendItemEntity时隐藏/显示系列。该代码有效,除了我使用系列的索引作为LegendItemCollection中LegendItem的索引。问题是有时会有比LegendItem更多的系列,它们各自的索引也不一样。如果我有LegendItemEntity,我如何得到LegendItem?
private final ChartMouseListener chartMouseListener = new ChartMouseListener() {
public void chartMouseClicked(ChartMouseEvent cme) {
ChartEntity entity = cme.getEntity();
if (entity instanceof LegendItemEntity) {
LegendItemEntity itemEntity = (LegendItemEntity) entity;
int index = dataset.getSeriesIndex(itemEntity.getSeriesKey());
XYPlot plot = (XYPlot) chart.getPlot();
XYItemRenderer renderer = plot.getRenderer();
renderer.setSeriesVisible(index, !renderer.isSeriesVisible(index));
LegendItem legendItem = plot.getLegendItems().get(index);
if (renderer.isSeriesVisible(index)) {
legendItem.setLinePaint(renderer.getSeriesPaint(index));
} else {
legendItem.setLinePaint(Color.WHITE);
}
}
}
public void chartMouseMoved(ChartMouseEvent cme) {
}
};
答案 0 :(得分:0)
您可以使用renderer.getLegendItem()
。对于不可见的系列,结果为null
。给定JFreeChart chart
,chartMouseClicked()
实现可能如下所示:
@Override
public void chartMouseClicked(ChartMouseEvent e) {
ChartEntity entity = e.getEntity();
if (entity instanceof LegendItemEntity) {
LegendItemEntity itemEntity = (LegendItemEntity) entity;
Comparable key = itemEntity.getSeriesKey();
XYDataset dataset = (XYDataset) itemEntity.getDataset();
int seriesIndex = dataset.indexOf(key);
XYPlot plot = (XYPlot) chart.getPlot();
int datasetIndex = plot.indexOf(dataset);
XYItemRenderer renderer = plot.getRenderer();
LegendItem legendItem = renderer.getLegendItem(datasetIndex, seriesIndex);
System.out.println(key + " " + datasetIndex + " " + seriesIndex);
System.out.println(legendItem);
}
}