drag a point on chart

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
pipodnmy
Posts: 1
Joined: Thu Dec 17, 2015 4:50 pm
antibot: No, of course not.

drag a point on chart

Post by pipodnmy » Thu Dec 17, 2015 4:59 pm

Hi
apologies if this is too obvious but i searched around the forum for a solution and couldnt find one.
Turns out it is super easy to drag a point - just implement a ChartMouseListener :

Code: Select all

  @Override
    public void chartMouseClicked(ChartMouseEvent event) {
        if (ts!=null) {
            ts = null;
            chart.chartpanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
        if (event.getEntity() instanceof XYItemEntity) {
            selected(event);
        }
    }
    protected void selected(ChartMouseEvent event) {
        selected = (XYItemEntity) event.getEntity();
        ts = ((TimeSeriesCollection) selected.getDataset()).getSeries(selected.getSeriesIndex());
        xy = ts.getDataItem(selected.getItem());
        chart.chartpanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
    @Override
    public void chartMouseMoved(ChartMouseEvent event) {
        if (ts!=null){
            moveTo(chart.plot.getRangeAxis().java2DToValue(event.getTrigger().getY(), chart.chartpanel.getChartRenderingInfo().getPlotInfo().getDataArea(), chart.plot.getRangeAxisEdge()));
        }
    }
    protected void moveTo(double yNew) {
        ts.delete(xy.getPeriod());
        xy.setValue(yNew);
        ts.add(xy);
    }
That's it. The behavior is : user clicks on any point (cursor changes to a hand to provide visual feedback that the point was locked successfully) , then starts dragging the mouse and the point moves with each mouse drag. I am not interested in changing the x coordinate so only look at the y of each point of the drag. On a second click, just reset the cursor and unselect the point. The last drag would have moved it correctly where it's supposed to be.

HTH

Locked