1

I have 4 series plotted on XYPlot. I want to obtain series ID when I click on XYPlot (see //int seriesId = ???;). Is it possible?

   _chartPanel.addChartMouseListener(new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent cme) 
        {
            MouseEvent me = cme.getTrigger();
            XYPlot plot = (XYPlot) cme.getChart().getPlot();
            if (me.getClickCount() == 2)
            {
                plot.clearAnnotations();
            }
            else
            {
                Rectangle2D dataArea = _chartPanel.getScreenDataArea();
                plot.clearAnnotations();
                ValueAxis xAxis = plot.getDomainAxis();
                ValueAxis yAxis = plot.getRangeAxis();
                double x = xAxis.java2DToValue(cme.getTrigger().getX(), dataArea, RectangleEdge.BOTTOM);
                double y = yAxis.java2DToValue(cme.getTrigger().getY(), dataArea, RectangleEdge.LEFT);
                if (!xAxis.getRange().contains(x)) { 
                    x = Double.NaN;                  

                //int seriesId = ???;

                DecimalFormat df = new DecimalFormat("#.##");
                df.setRoundingMode(RoundingMode.CEILING);
                XYPointerAnnotation pt = new XYPointerAnnotation("Lat: " + df.format(y) + "\n Lon: " + df.format(x), x, y, 0.2);
                pt.setBackgroundPaint(new Color(103,154,236));
                // pt.setArrowPaintnew Color(103,154,236)d);
                pt.setFont(_font);
                pt.setPaint(Color.LIGHT_GRAY);
                plot.addAnnotation(pt);
            }
        }
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217

1 Answers1

2

As shown here, you can retrieve the ChartEntity from the ChartMouseEvent. For a ChartEntity of type XYItemEntity, you can get the dataset via getDataset() and the series index via getSeriesIndex().

ChartEntity ce = cme.getEntity();
if (ce instanceof XYItemEntity) {
    XYItemEntity e = (XYItemEntity) ce;
    System.out.println("Dataset: " + e.getDataset());
    System.out.println("Series index: " + e.getSeriesIndex());
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Thank you. I tested your solution. For some reason I always get `Series index:0`, doesn't matter which series do I click on. P.S. I create series as follows: `for (int i=0; i<_dataset.size(); i++) _chart.getXYPlot().setDataset(i,_dataset.get(i));`, where `dataset` is `List`. Then I define a separate renderer for each `XYDataset` in order to specify a color and other features. – Klausos Klausos Feb 08 '16 at 20:58
  • Use the result from `getDataset()` to query your `List`; more above. – trashgod Feb 08 '16 at 23:20
  • 1
    Before the line `XYDataset d = e.getDataset();` probably some other line is missed, because `e` is undefined. – Klausos Klausos Feb 09 '16 at 08:57